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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With