2016-10-26 9 views
1

私は以下のクラスを持っています。しかし、データベースで生成されたテーブルで、私はABテーブルで見つかった:Entity Frameworkはデータベースに余分な外部キーを生成します

それは、彼らはまた、外部キーであることをそこAID1 & AID2すべきではない二つの追加列になってどのように
Id, AId, BId 

。 ABMapping

クラスA

public class A 
{ 
    public int Id { get; set; } 
    ICollection<AB> ABs { get; set; } 
} 

クラスB

public class B 
{ 
    public int Id { get; set; } 
    ICollection<AB> ABs { get; set; } 
} 

AB級

public class AB 
{ 
    public int Id { get; set; } 
    public A A { get; set; } 
    public B B { get; set; } 
    public int AId { get; set; } 
    public int BId { get; set; } 
} 

public class ABMap : EntityTypeConfiguration<AB> 
{ 
     public ABMap() 
     { 
      this.HasKey(a => a.Id); 

      this.HasRequired(e => e.A) 
       .WithMany() 
       .HasForeignKey(e => e.AId) 
       .WillCascadeOnDelete(false); 

      this.HasRequired(c => c.B) 
       .WithMany() 
       .HasForeignKey(e => e.BId) 
       .WillCascadeOnDelete(false); 

      this.Property(e => e.AId) 
        .HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("IX_AB", 1) { IsUnique = true })); 
      this.Property(e => e.BId) 
        .HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("IX_AB", 2) { IsUnique = true })); 
     } 
    } 

コンテキスト

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
{ 
     //... 
     modelBuilder.Configurations.Add(new ABMap()); 
     //... 
} 

答えて

1

はあなたがWithManyを呼び出すときに、コレクションのプロパティを指定する必要があります。 EFに対して、2つのABsコレクションが定義した関係の一部であると言うと、2つの追加の1対多の関係が作成されます。流暢なAPIマッピングを次のように変更します。

public class ABMap : EntityTypeConfiguration<AB> 
{ 
    public ABMap() 
    { 
     this.HasKey(a => a.Id); 

     this.HasRequired(e => e.A) 
      .WithMany(a => a.ABs) 
      .HasForeignKey(e => e.AId) 
      .WillCascadeOnDelete(false); 
     this.Property(a => a.AId); 

     this.HasRequired(c => c.B) 
      .WithMany(b => b.ABs) 
      .HasForeignKey(e => e.BId) 
      .WillCascadeOnDelete(false); 
     this.Property(a => a.BId); 

     this.Property(e => e.AId) 
       .HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("IX_AB", 1) { IsUnique = true })); 
     this.Property(e => e.BId) 
       .HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("IX_AB", 2) { IsUnique = true })); 
    } 
} 
関連する問題