I'm trying this class:
public class Person
{
public int PersonID { get; set; }
public string Name { get; set; }
public int SpouseID { get; set; }
public virtual Person Spouse { get; set; }
}
The relationship is: One Person has one or zero Spouse / One Spouse has a required Person
Is it possible to build this model in Fluent API?
Thanks.
Unfortunately it is not possible to make real self referencing one-to-one relation because at the moment EF doesn't support unique keys. To make this real self referencing one-to-one SpouseID
must be marked as unique. EF allows one-to-one only on primary keys (primary key in dependent entity must be also foreign key to principal entity) which means that self referencing one-to-one relation would end in PersonID <-> PersonID
= two entities with same PersonID
in single table. It is not possible because PersonID
is primary key and it must be unique.
You can handle it as one-to-many and expose only single navigation property as you do know:
modelBuilder.Entity<Person>()
.HasOptional(p => p.Spouse)
.WithMany()
.HasForeingKey(s => s.SpouseID);
To enforce one-to-one relation in database you will add custom database initializer and manually create unique index on SpouseID
column.
The problem is that it is only one way navigation so you can get Person's spouse but from that Spouse
you cannot get back to husband.
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