【问题标题】:Display UserName and Role in MVC4在 MVC4 中显示用户名和角色
【发布时间】: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&lt;UserProfile&gt;UserRole 导航到UserProfile?考虑删除此集合。也就是说,您的错误消息提到了UserProfiles,其中此集合被命名为UserProfile。可能是某个地方的拼写错误?
  • 删除 'ICollection' 后出现错误:'Invalid column name 'UserProfile_UserId'。\r\nInvalid column name 'UserProfile_UserId'。'
  • 似乎需要重新生成数据库。

标签: asp.net-mvc asp.net-mvc-4


【解决方案1】:

看来问题出在这里

public virtual ICollection<UserRole> UserRole { get; set; }

而且你没有这些类的映射,所以默认设置创建一个UserRoleUserProfiles表(或类)并且它在数据库中不存在,所以问题就出现了。

您可以尝试删除这行代码,然后再次尝试运行项目

【讨论】:

猜你喜欢
  • 2013-02-26
  • 2021-04-06
  • 2021-12-01
  • 1970-01-01
  • 2016-09-09
  • 1970-01-01
  • 2015-09-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多