我在公司和CompanyDemographics之间建立了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");
}
它试图删除所有密钥并重建。我该如何避免这种情况?
答案 0 :(得分:0)
将@Steve Greene评论转换为答案:
将[InverseAttribute(&#34; Company&#34;)]放在公司的人口统计属性(而不是ForeignKey)上解决了它!
[InverseAttribute("Company")]
public virtual CompanyDemographic Demographic { get; set; }