2013-12-19 30 views
1

我想创建一个用于编辑用户角色的简单管理面板。首先,我想要显示其角色的用户列表。在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'。”。我不太明白。有人能解释我为什么会发生这种情况,以及如何解决这个问题?

+0

你曾经需要通过'ICollection的''从到UserRole''UserProfile'导航?考虑删除这个集合。也就是说,你的错误信息提到'UserProfiles',这个集合被命名为'UserProfile'。可能是拼写错误的地方? –

+0

删除'ICollection '后,我收到错误:'无效的列名'UserProfile_UserId'。\ r \ n无效的列名'UserProfile_UserId'。' – Placek

+0

似乎需要重新生成数据库。 –

回答

1

好像问题就出在这里

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

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

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

+0

如果我删除该行,我得到指定的包含路径无效。但是我需要它,否则我会得到“数据在连接完成之前已经处理完毕”。 – Placek

+0

你有没有考虑过使用映射? [NHibernate](http://nhforge.org/),[流利NHibernate](http://www.fluentnhibernate.org/),[实体框架映射](http://msdn.microsoft.com/en-us /data/jj591617.aspx) – albusshin

相关问题