在EF / MVC6中定义外键关系

时间:2016-02-28 20:06:15

标签: asp.net-mvc entity-framework ef-code-first

我已在模板模型中扩展ApplicationUser类,以包含可选公司:

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; }

我是否还需要在ModelBuilder的{​​{1}}中指定关系?或Code-First应该为我处理这个问题吗?

我问,因为当我在控制器ApplicationdbContext中抓取_context.Users.ToList()始终为Company时,即使为null填充了CompanyID

1 个答案:

答案 0 :(得分:1)

将模型更改为:

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

Config MolderBinder For ApplicationUser对此:

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