2016-02-28 85 views
0

我在模板模型擴展ApplicationUser類包括可選公司:定義外鍵關係在EF/MVC6

public class ApplicationUser : IdentityUser 
{ 
    public virtual Guid? CompanyID { get; set; } 

    public virtual Company Company { get; set; } 
} 

而在「公司」類我已經包括集合ApplicationUsers

[Required] 
    [Key] 
    public Guid? CompanyId { get; set; } 

    public virtual ICollection<ApplicationUser> Users { get; set; } 

難道我還需要指定ApplicationdbContextModelBuilder的關係?或應該Code-First爲我處理?

我問,因爲我在一個控制器搶_context.Users.ToList()Company總是null,即使CompanyID填充爲ApplicationUser

+0

那工作過。你介意解釋爲什麼? – jidl

+0

https://msdn.microsoft.com/en-us/library/gg671236%28v=vs.103%29.aspx#Anchor_1 –

回答

1

變化模型它:

[Required] 
[Key] 
public Guid CompanyId { get; set; } 
public virtual ICollection<ApplicationUser> Users { get; set; } 

和配置MolderBinder對於ApplicationUser要這樣:

modelBuilder.Entity<ApplicationUser>().HasOptional(row => row.Company).WithMany().HasForeignKey(row => row.CompanyID).WillCascadeOnDelete(false); 
+0

沒有'HasOptional'可用 - 什麼是命名空間? – jidl

+0

System.Data.Entity.ModelConfiguration –

+0

問題解決了嗎? –