2013-12-19 29 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

相關問題