同一父表的多个外键

时间:2013-10-18 17:17:21

标签: entity-framework ef-code-first entity-framework-5

我使用EF 5代码优先使用以下简化类,其中我的B类有多个FK指向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约束。 无法创建约束。查看以前的错误。

我尝试通过EntityTypeConfiguration修改级联规则:

        HasOptional(x => x.A1)
            .WithMany()
            .HasForeignKey(p => p.A1Id)
            .WillCascadeOnDelete(false);

还试过这个:

            HasOptional(x => x.A1)
            .WithMany()
            .Map(y => y.MapKey("A1Id"))
            .WillCascadeOnDelete(false);

遵循以下建议:Multiple foreign keys to same primary key table

但仍然有同样的错误。我所有的A1,A2和A3 FK都是可选的。

有关如何解决此错误的任何想法?

谢谢!

1 个答案:

答案 0 :(得分:2)

你必须修改你的类:

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更改为:

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);

这将为您提供以下表格结构:

Table Structure