我想創建一個用於編輯用戶角色的簡單管理面板。首先,我想要顯示其角色的用戶列表。在MVC4中顯示用戶名和角色
首先我編輯在AccountModel一些事情:
語境:
public class UsersContext : DbContext
{
public UsersContext()
: base("DefaultConnection")
{
}
public DbSet<UserProfile> UserProfiles { get; set; }
public DbSet<UserRole> UserRole { get; set; }
}
用戶配置文件:
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public string EmailId { get; set; }
public string Details { get; set; }
public virtual ICollection<UserRole> UserRole { get; set; }
}
用戶角色:
[Table("webpages_Roles")]
public class UserRole
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int RoleId { get; set; }
public string RoleName { get; set; }
public virtual ICollection<UserProfile> UserProfile { get; set; }
}
之後,我創建UserControll呃用的ActionResult指數:
public ActionResult Index()
{
using (var db = new UsersContext())
{
return View(db.UserProfiles.Include("UserRole").ToList());
}
}
,並查看:
@model IEnumerable<AnimeWeb.Models.UserProfile>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
User Name
</th>
<th>
User Role
</th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.UserName)
</td>
<td>
@Html.DisplayFor(modelItem => item.UserRole)
</td>
</tr>
}
管窺UserRole的是這樣的:
@model AnimeWeb.Models.UserRole
<tr>
@Html.DisplayFor(model => model.RoleName),
</tr>
當我嘗試執行它我得到了InnerException錯誤:「無效的對象名'dbo.UserRoleUserProfiles'。」。我不太明白。有人能解釋我爲什麼會發生這種情況,以及如何解決這個問題?
你曾經需要通過'ICollection的''從到UserRole''UserProfile'導航?考慮刪除這個集合。也就是說,你的錯誤信息提到'UserProfiles',這個集合被命名爲'UserProfile'。可能是拼寫錯誤的地方? –
刪除'ICollection'後,我收到錯誤:'無效的列名'UserProfile_UserId'。\ r \ n無效的列名'UserProfile_UserId'。' –
Placek
似乎需要重新生成數據庫。 –