使用:VS 2013,实体框架代码优先,ASP.NET Web项目MVC
我有2个型号,同一个表需要2个FK:
public class A
{
public int Id { get; set; }
public string Name { get; set; }
}
public class B
{
public int Id { get; set; }
public int Id1 { get; set; }
[ForeignKey("Id1")]
public virtual A A1 { get; set; }
public int Id2 { get; set; }
[ForeignKey("Id2")]
public virtual A A2 { get; set; }
}
在enable-migration
和Add-Migration Test
之后,当我运行Update-Database
时,我收到此消息:
在表'B'上引入FOREIGN KEY约束'FK_dbo.B_dbo.A_Id2'可能会导致循环或多个级联路径。指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN KEY约束。
答案 0 :(得分:0)
使用此代码
public class A
{
public int Id { get; set; }
public string Name { get; set; }
}
public class B
{
public int Id { get; set; }
public int Id1 { get; set; }
[ForeignKey("Id1")]
public virtual A A1 { get; set; }
public int Id2 { get; set; }
[ForeignKey("Id2")]
public virtual A A2 { get; set; }
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<B>()
.HasRequired(e => e.A1)
.WithMany()
.HasForeignKey(c => c.Id1)
.WillCascadeOnDelete(false)
.HasRequired(e => e.A2)
.WithMany()
.HasForeignKey(c => c.Id2)
.WillCascadeOnDelete(false)
;
}
另外你可以使用inverseProperty属性。