Simply, in C# EF6, how do you map two navigation properties to the same table while keeping their result sets separate? In plain English, I have a class that I want two collections of in another class. In other words, I want two collections of the same type but with different elements. Unfortunately, EF6 seems to treat both collections the same and gives them both the same elements (every record in the table).
The best I found from dozens of StackOverflow answers was this, but it has the problem described. In this example, a Father has many Sons and many Daughters, and they each have the one Father. Ideally, both Sons and Daughters can be stored in the same table 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);
}
The problem with this is, when reading the data back from the Child table, it doesn't discriminate between Sons and Daughters. That is, the Sons collection will not only contain Sons but also Daughters, and so will the Daughters collection. I might have expected EF6 to try to use a discriminator column, but it doesn't.
Question: How do you map two navigation properties to the same table and still be able to read its records back into their corresponding navigation properties? Or, is the example correct, and my problem is elsewhere? Or, is this not possible, and they need to be mapped to their own tables (with identical schemas).