我有以下课程,一切都很好。但是在我在AB
表中找到的数据库中生成的表中:
Id, AId, BId
它应该是怎么样的,另外两列不应该是AId1& AId2他们也是外键。
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; }
}
ABMapping
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());
//...
}
答案 0 :(得分:1)
您需要在致电WithMany
时指定集合属性。因为您没有告诉EF两个ABs
集合是您定义的关系的一部分,所以创建了两个额外的一对多关系。将您的流畅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 }));
}
}