代码之家  ›  专栏  ›  技术社区  ›  mbursill

当相关表首先引用时,一对一上的EF迁移问题

  •  1
  • mbursill  · 技术社区  · 7 年前

    我在公司和公司之间有一种1:1的关系,就像这样创建的图表:

    public class Company
    {
        public Company()
        {
            Contacts = new HashSet<Contact>();
        }
    
        [Key]
        public int CompanyId { get; set; }
    
        public string Name { get; set; }
    
        [ForeignKey("CompanyId")]
        public virtual CompanyDemographic Demographic { get; set; }
    
        public virtual ICollection<Contact> Contacts { get; set; }
    }
    
    public class CompanyDemographic
    {
        [Key]
        [ForeignKey("Company")]
        public int CompanyId { get; set; }
        public virtual Company Company { get; set; }
    
        public int EmployeeCount { get; set; }
    }
    

    迁移构建正确,一切正常。

    然后,我在CompanyDemographic中添加了一个引用,如下所示:

    public class CompanyDemographic
    {
        [Key]
        [ForeignKey("Company")]
        public int CompanyId { get; set; }
        public virtual Company Company { get; set; }
    
        public int EmployeeCount { get; set; }
    
        // ADDING THIS
        [ForeignKey("CurrentProvider")]
        public int CurrentProviderCompanyId { get; set; }
        public virtual Company CurrentProvider { get; set; }
    }
    

    当我添加迁移时,看起来是这样的:

    public override void Up()
    {
        DropForeignKey("dbo.Contacts", "CompanyId", "dbo.Companies");
        DropForeignKey("dbo.CompanyDemographics", "CompanyId", "dbo.Companies");
        DropPrimaryKey("dbo.Companies");
        AddColumn("dbo.CompanyDemographics", "CurrentProviderCompanyId", c => c.Int(nullable: false));
        AlterColumn("dbo.Companies", "CompanyId", c => c.Int(nullable: false));
        AddPrimaryKey("dbo.Companies", "CompanyId");
        CreateIndex("dbo.Companies", "CompanyId");
        CreateIndex("dbo.CompanyDemographics", "CurrentProviderCompanyId");
        AddForeignKey("dbo.CompanyDemographics", "CurrentProviderCompanyId", "dbo.Companies", "CompanyId", cascadeDelete: true);
        AddForeignKey("dbo.Contacts", "CompanyId", "dbo.Companies", "CompanyId", cascadeDelete: true);
        AddForeignKey("dbo.CompanyDemographics", "CompanyId", "dbo.Companies", "CompanyId");
    }
    

    它试图删除所有的键并重建。如何避免这种情况?

    1 回复  |  直到 7 年前
        1
  •  0
  •   objectively C    7 年前

    将@Steve Greene的评论转换为答案:


    将[InverseatAttribute(“Company”)]放在公司的人口统计属性上(而不是ForeignKey)解决了这个问题!

    [InverseAttribute("Company")]
    public virtual CompanyDemographic Demographic { get; set; }