【问题标题】:Defining Foreign Key Relationships in EF / MVC6在 EF / MVC6 中定义外键关系
【发布时间】:2016-06-11 18:52:43
【问题描述】:

我在模板模型中扩展了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 中为ApplicationdbContext 指定关系?还是 Code-First 应该为我处理这个问题?

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

【问题讨论】:

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


【解决方案1】:

将模型更改为它:

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

并为 ApplicationUser 配置 MolderBinder 到这个:

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

【讨论】:

  • 没有可用的HasOptional - 命名空间是什么?
  • System.Data.Entity.ModelConfiguration
  • 还没有!该命名空间似乎不可用 - 是否已为 DNX 5 做好准备?
  • 是的,有以下参考资料吗? EntityFramework , System.ComponentModel.DataAnnotations , System.Core , System.Data
  • 请参阅 stackoverflow.com/q/35562483/2591770 - 我认为 HasOptional 已从 EF7 / Core 中删除
猜你喜欢
  • 1970-01-01
  • 2011-07-23
  • 1970-01-01
  • 2021-12-12
  • 1970-01-01
  • 2021-03-01
  • 1970-01-01
  • 2018-05-31
  • 2020-12-10
相关资源
最近更新 更多