多个外键到同一个父表 [英] Multiple foreign keys to the same parent table
问题描述
我有以下使用EF 5代码的简化类,其中我的B类有多个FK指向A类。
I have the following simplified classes using EF 5 code-first, where my class B has multiple FK's pointing back to class A.
public class A
{
public int Id {get;set;}
ICollection<B> Bs {get;set;}
}
public class B
{
public int Id {get;set;}
public int A1Id {get;set;}
public int A2Id {get;set;}
public int A3Id {get;set;}
[ForeignKey("A1Id")]
public A A1 {get;set;}
[ForeignKey("A2Id")]
public A A2 {get;set;}
[ForeignKey("A3Id")]
public A A3 {get;set;}
}
当我尝试建立我的表我得到这个错误:
表B上的FOREIGN KEY约束'FK_dbo.B_dbo.A_A1Id'可能会导致循环或多个级联路径。指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN KEY约束。
无法创建约束。查看以前的错误。
When I try to build my table I get this error: Introducing FOREIGN KEY constraint 'FK_dbo.B_dbo.A_A1Id' on table 'B' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. Could not create constraint. See previous errors.
我尝试通过EntityTypeConfiguration修改级联规则:
I tried modifying the cascade rules through a EntityTypeConfiguration:
HasOptional(x => x.A1)
.WithMany()
.HasForeignKey(p => p.A1Id)
.WillCascadeOnDelete(false);
还尝试过:
HasOptional(x => x.A1)
.WithMany()
.Map(y => y.MapKey("A1Id"))
.WillCascadeOnDelete(false);
遵循以下建议:多个外键到同一主键表
但仍然有相同的错误。所有我的A1,A2和A3 FK都是可选的。
But still got the same error. All my A1,A2 and A3 FK are optional.
有关如何解决这个错误的任何想法?
Any ideas on how to get around this error?
谢谢!
推荐答案
你必须像这样修改你的课程:
You have to modify your classes like so:
public class A
{
public int Id { get; set; }
public virtual ICollection<B> B1s { get; set; }
public virtual ICollection<B> B2s { get; set; }
public virtual ICollection<B> B3s { get; set; }
}
public class B
{
public int Id { get; set; }
public int? A1Id { get; set; }
public int? A2Id { get; set; }
public int? A3Id { get; set; }
public virtual A A1 { get; set; }
public virtual A A2 { get; set; }
public virtual A A3 { get; set; }
}
更改您的 Fluent API
to this:
Change your Fluent API
to this:
modelBuilder.Entity<B>()
.HasOptional(b => b.A1)
.WithMany(a => a.B1s)
.HasForeignKey(k => k.A1Id)
.WillCascadeOnDelete(false);
modelBuilder.Entity<B>()
.HasOptional(b => b.A2)
.WithMany(a => a.B2s)
.HasForeignKey(k => k.A2Id)
.WillCascadeOnDelete(false);
modelBuilder.Entity<B>()
.HasOptional(b => b.A3)
.WithMany(a => a.B3s)
.HasForeignKey(k => k.A3Id)
.WillCascadeOnDelete(false);
这将给你以下表格结构:
This will give you the following table structure:
这篇关于多个外键到同一个父表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!