The first entity code is combining 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 when the type is initial.

The specified schema is invalid. Errors: (151.6): error 0040: The Person_Father type is not defined in the ExamModel namespace (Alias ​​= Self).

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

+6
source share
2 answers

It is not possible to match two navigation properties with one collection property. It looks like a mockery, but you must 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); } } 
+14
source

Thank you, Erang, your answer is exactly what I need!

Also, here is the modelBuilder code if someone uses this 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); } 
+2
source

Source: https://habr.com/ru/post/907318/


All Articles