简单地说,在 C# EF6 中,如何将两个导航属性映射到同一个表,同时保持它们的结果集分开?用简单的英语来说,我有一个类(class),我想要另一个类(class)的两个集合。换句话说,我想要两个类型相同但元素不同的集合。不幸的是,EF6 似乎对这两个集合一视同仁,并为它们提供了相同的元素(表中的每条记录)。
我从数十个 StackOverflow 答案中找到的最好答案是这个,但它描述了问题。在这个例子中,一个父亲有很多儿子和很多女儿,他们每个人都有一个父亲。理想情况下,Sons 和 Daughters 都可以存储在同一个表 Child 中。
class Father
{
[Key]
public long Id { get; set; }
public virtual ICollection<Child> Sons { get; set; }
public virtual ICollection<Child> Daughters { get; set; }
}
class Child
{
[Key]
public long Id { get; set; }
public long FatherId_1 { get; set; }
public Father Father_1 { get; set; }
public long FatherId_2 { get; set; } // One for each collection???
public Father Father_2 { get; set; }
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Child>()
.HasRequired(e => e.Father_1)
.WithMany(e => e.Sons)
.HasForeignKey(e => e.FatherId_1);
modelBuilder.Entity<Child>()
.HasRequired(e => e.Father_2)
.WithMany(e => e.Daughters)
.HasForeignKey(e => e.FatherId_2);
}
问题在于,当从Child 表中读回数据时,它不会区分Sons 和Daughters。也就是说,Sons 集合不仅包含Sons,还包含Daughters,Daughters 集合也是如此。我可能期望 EF6 尝试使用鉴别器列,但事实并非如此。
问题:如何将两个导航属性映射到同一个表,并且仍然能够将其记录读回到它们相应的导航属性中?或者,示例是否正确,而我的问题在其他地方?或者,这是不可能的,它们需要映射到它们自己的表(具有相同的模式)。
最佳答案
我对你的解释有点困惑。但是我找到了一些我理解的代码:
对于“这是一个模型‘Child’,需要拆分成两个集合”:
modelBuilder.Entity<Child>()
.Map(m =>
{
m.Properties(t => new { t.Id /*other props*/ });
m.ToTable("Sons");
})
.Map(m =>
{
m.Properties(t => new { t.Id /*other props*/});
m.ToTable("Daughters");
});
关于C#EF6 : Two navigation properties of the same type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45970846/