2017-09-13 45 views
1

我正在玩ASP.NET身份,使用MVC5和EntityFramework 6.1.3。 我的問題是我無法將IdentityUser作爲屬性添加到另一個模型。添加IdentityUser作爲其他模型的屬性

我的應用程序可以讓用戶創建一個項目:

public class Project 
    { 
     public int ProjectID { get; set; } 
     public string ProjectName { get; set; } 
     public virtual ApplicationUser ApplicationUser { get; set; } 
    } 

在創建新項目的操作方法,我想添加在用戶簽訂這樣的:

public ActionResult Create([Bind(Include = "ProjectID,ProjectName")] Project project) 
     { 
      if (ModelState.IsValid) 
      { 
       // I added the first two lines of code below. 
       var loggedInUser = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId()); 
       project.ApplicationUser = loggedInUser; 
       db.Projects.Add(project); 
       db.SaveChanges(); 
       return RedirectToAction("Index"); 
      } 

      return View(project); 
     } 

loggedInUser設置正確,它獲取所有正確的屬性。然而,當我嘗試保存更新的情況下,我得到以下錯誤:

"Validation failed for one or more entities. The validation errors are: User name [email protected] is already taken." 

所以,由於某種原因,我的代碼顯然是試圖代替將現有的創建項目,以創建一個新用戶。爲什麼? 這不是將IdentityUser作爲導航屬性添加到模型的方式嗎?

+0

兩項一般性意見,爲什麼你就不能在用戶ID存儲爲類的屬性,並根據需要進行身份用戶查找。似乎更多的資源高效。爲什麼你不能讓這個類繼承自身份用戶模型?我認爲一般而言,您的問題是在保存新模型更改過程中所考慮的問題,它正在嘗試保存重複,就像錯誤所述。您需要在那裏解決任何身份用戶的一個實體並引用它,而不是嘗試重新保存重複數據。這正是身份意味着唯一的一個。 –

回答

2

我想你有two一對多relationship

Project實體可以只有一個user附加和user實體可以有一個或多個projects

因此,你需要附加的外鍵在Project類以正確允許Entity frameworkmap關係,並建立relational模型(數據庫)和conceptual模型之間 關聯。

public class Project 
{ 
    public int ProjectID { get; set; } 
    public string ProjectName { get; set; } 
    public int ApplicationUserId{ get; set;} 
    public virtual ApplicationUser ApplicationUser { get; set; } 
}