Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One to zero/one relationship (Code First)

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.

like image 664
Joao Avatar asked Aug 11 '11 20:08

Joao


1 Answers

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.

like image 134
Ladislav Mrnka Avatar answered Oct 07 '22 22:10

Ladislav Mrnka