我正在努力解决两种不同寻常的关系。我还没有找到一种方法来告诉" EF如何正确构建其模型。我在这里使用精简课程来专注于关系。它们似乎不是通常的1-1,1-M,M-M模具。
第一
public class Parent1 {
public int Id { get; set; }
public string Description { get; set; }
public ICollection<Child> Children { get; set; }
}
public class Parent2 {
public int Id { get; set; }
public string Description { get; set; }
public ICollection<Child> Children { get; set; }
}
public class Child {
public int Id { get; set; }
public string OtherStuff { get; set; }
public int Parent1Id { get; set; }
public Parent1 Parent1 { get; set; }
public int Parent2Id { get; set; }
public Parent2 Parent2 { get; set; }
}
and my fluent API
modelBuilder.Entity<Parent1>()
.HasMany(c => c.Children)
.WithOne(d => d.Parent1)
.HasForeignKey(c => c.Parent1Id)
.IsRequired()
.OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<Parent2>()
.HasMany(c => c.Children)
.WithOne(d => d.Parent2)
.HasForeignKey(c => c.Parent2Id)
.IsRequired()
.OnDelete(DeleteBehavior.Cascade);
EF似乎不喜欢从两个方向级联删除。
第二
public class Parent {
public int Id { get; set; }
public string Description { get; set; }
public ICollection<Child> Children { get; set; }
}
public class Child {
public int Id { get; set; }
public string OtherStuff { get; set; }
public int Parent1Id { get; set; } // Think "Mail to"
public Parent Parent1 { get; set; }
public int Parent2Id { get; set; } // Think "Bill To". Same table, different purpose
public Parent Parent2 { get; set; }
}
and my fluent API
modelBuilder.Entity<Parent>()
.HasMany(c => c.Children)
.WithOne(d => d.Parent1)
.HasForeignKey(c => c.Parent1Id)
.IsRequired()
.OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<Parent>()
.HasMany(c => c.Children)
.WithOne(d => d.Parent2)
.HasForeignKey(c => c.Parent2Id)
.IsRequired()
.OnDelete(DeleteBehavior.Cascade);
EF并不喜欢指向同一实体中的两个父母。