Reputation: 181
I have a couple of entity classes.
Parent:
public class Parent
{
public Parent()
{
}
public int ParentId { get; set; }
public virtual Child Boy { get; set; }
public virtual Child Girl { get; set; }
}
and Child:
public class Child
{
public int ChildId { get; set; }
public virtual Parent Parent { get; set; }
}
So, Parent has 2 one-to-one relationships with Child.
In OnModelCreating, I added the following:
modelBuilder.Entity<Parent>()
.HasKey<int>(e => e.ParentId);
modelBuilder.Entity<Child>()
.HasKey<int>(e => e.ChildId);
modelBuilder.Entity<Parent>()
.HasOptional<Child>(p => p.Boy)
.WithRequired(c => c.Parent)
.WillCascadeOnDelete(true);
modelBuilder.Entity<Parent>()
.HasOptional<Child>(p => p.Girl)
.WithRequired(c => c.Parent)
.WillCascadeOnDelete(true);
But I get an error when creating the database:
Schema specified is not valid. Errors: The relationship 'Example.Parent_Boy' >was not loaded because the type 'Example.Child' is not available.
How can I configure the model so that my entity can have 2 nullable, one-to-one relationships to the same entity type?
Upvotes: 0
Views: 45
Reputation: 301
You can try this :
public Parent()
{
}
public int ParentId { get; set; }
public virtual List<Child> Children { get; set; }
public Child Boy{ get{ return Children.First(<BoyCondition>); } }
public Child Girl{ get{ return Children.First(<GirlCondition>); } }
Dont forget to ignore boy and girl propertys
modelBuilder.Entity<Parent>().Ignore(m => m.Boy);
modelBuilder.Entity<Parent>().Ignore(m => m.Girl);
Upvotes: 1