我已在模板模型中扩展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
。
答案 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);