C#EF6 : Two navigation properties of the same type

标签 c# entity-framework-6

简单地说,在 C# EF6 中,如何将两个导航属性映射到同一个表,同时保持它们的结果集分开?用简单的英语来说,我有一个类(class),我想要另一个类(class)的两个集合。换句话说,我想要两个类型相同但元素不同的集合。不幸的是,EF6 似乎对这两个集合一视同仁,并为它们提供了相同的元素(表中的每条记录)。

我从数十个 StackOverflow 答案中找到的最好答案是这个,但它描述了问题。在这个例子中,一个父亲有很多儿子和很多女儿,他们每个人都有一个父亲。理想情况下,SonsDaughters 都可以存储在同一个表 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 表中读回数据时,它不会区分SonsDaughters。也就是说,Sons 集合不仅包含Sons,还包含DaughtersDaughters 集合也是如此。我可能期望 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/

相关文章:

c# - EF Core 6 启动项目在尝试搭建非启动项目的项目时不引用 EFCore.Design

c# - Azure webapp 502.5错误,突然出现

c# - 始终在底部滚动文本框

entity-framework - 在 Entity Framework 中创建双链表

c# - 具有多个连接的 Linq 查询未给出正确的结果

c# - 如何使用 ServiceStack OrmLite 从 SQLite 读取 PRAGMA?

c# - System.DirectoryServices.DirectoryEntry 是否包含一个实际使用 "domain\username"和 Ldap 的构造函数?

c# - 如何在 Entity Framework 和 Mysql 中使用规范函数

c# - 在自定义类中为 Entity Framework 实现IDisposable

c# - 如何制作 Optional 1 :1 Relationship in EF6 with the same Entity Type on both sides?