我想创建一个用于编辑用户角色的简单管理面板。首先,我想要显示其角色的用户列表。在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
似乎需要重新生成数据库。 –