简体   繁体   中英

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)?

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);
     }
 }

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM