【发布时间】:2013-12-19 11:52:20
【问题描述】:
我想创建一个简单的管理面板来编辑用户角色。首先,我想显示用户列表及其角色。
首先我在 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; }
}
之后我用 ActionResult Index 创建了 UserController:
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<UserProfile>从UserRole导航到UserProfile?考虑删除此集合。也就是说,您的错误消息提到了UserProfiles,其中此集合被命名为UserProfile。可能是某个地方的拼写错误? -
删除 'ICollection
' 后出现错误:'Invalid column name 'UserProfile_UserId'。\r\nInvalid column name 'UserProfile_UserId'。' -
似乎需要重新生成数据库。