Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

entity framework code first - Union of the two fields into one collection

i have this model and configuration

public class Person
 {
     public int? FatherId { get; set; }
     public virtual Person Father { get; set; }
     public int? MotherId { get; set; }
     public virtual Person Mother { get; set; }
     public virtual List<Person> Childs { get; set; }

 }
 class PersonConfiguration : EntityTypeConfiguration<Person>
 {
     public PersonConfiguration()
     {
         HasOptional(e => e.Father).WithMany(e => e.Childs)
              .HasForeignKey(e => e.FatherId);
         HasOptional(e => e.Mother).WithMany(e => e.Childs)
              .HasForeignKey(e => e.MotherId);
     }
 }

and i get this error where the type is initial.

Schema specified is not valid. Errors: (151,6) : error 0040: Type Person_Father is not defined in namespace ExamModel (Alias=Self).

Is there a way to map Childs property by both properties (motherId and fatherId)?

like image 222
mordechai Avatar asked Jan 31 '12 14:01

mordechai


2 Answers

Its not possible to map two navigational properties to a single collection property. It looks ridicules but you have to have two collection properties

public class Person
 {
     public int? FatherId { get; set; }
     public virtual Person Father { get; set; }
     public int? MotherId { get; set; }
     public virtual Person Mother { get; set; }
     public virtual List<Person> ChildrenAsFather { get; set; }
     public virtual List<Person> ChildrenAsMother { get; set; }
 }

 class PersonConfiguration : EntityTypeConfiguration<Person>
 {
     public PersonConfiguration()
     {
         HasOptional(e => e.Father).WithMany(e => e.ChildrenAsFather)
              .HasForeignKey(e => e.FatherId);
         HasOptional(e => e.Mother).WithMany(e => e.ChildrenAsMother)
              .HasForeignKey(e => e.MotherId);
     }
 }
like image 126
Eranga Avatar answered Oct 31 '22 08:10

Eranga


Thank you, Eranga, your reply is exactly what I needed!

Additionally, here is the modelBuilder code if anyone is using that method instead of the configuration method that Eranga used.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Person>().
    HasKey(i => i.PersonId);

    modelBuilder.Entity<Person>().
    HasOptional(f => f.Father).
    WithMany(f => f.ChildrenAsFather).
    HasForeignKey(f => f.FatherId);

    modelBuilder.Entity<Person>().
    HasOptional(m => m.Mother).
    WithMany(m => m.ChildrenAsMother).
    HasForeignKey(m => m.MotherId);
}
like image 40
pitt09 Avatar answered Oct 31 '22 08:10

pitt09