2

In this question (What does principal end of an association means in 1:1 relationship in Entity framework) the best answer says :

In one-to-one relation one end must be principal and second end must be dependent. Principal end is the one which will be inserted first and which can exist without the dependent one. Dependent end is the one which must be inserted after the principal because it has foreign key to the principal.

I wonder, how can I implement one-to-one relationship in Entity Framework where there are no principal and dependent elements? For example :

public class Person {
    public int Id {get;set;}
    public string Name {get;set;}
    public Person Spouse {get;set;}
}

Each person may or may not have another one as Spouse. If in one-to-one must sutisfy for the existence of principal and dependent elements, so, where in this Person model principal and where dependent ones?

Iskander Raimbaev
  • 1,322
  • 2
  • 17
  • 35
  • [This](http://stackoverflow.com/questions/24262172/parent-child-one-to-one-relation-same-table) is an old question... don't know if still the case – Gilad Green Oct 05 '16 at 18:34
  • 1
    @GiladGreen, oh, I see. Does this problem still exist on EF6 or even in EF One? Consequently, the only way - to use one-to-many, am I right? – Iskander Raimbaev Oct 05 '16 at 18:39
  • 1
    unfortunately I don't know and don't have much experience with EF.. I came across this when looking for similar questions - That is why I also stated that it is an old post – Gilad Green Oct 05 '16 at 18:41
  • 1
    It's not just an EF problem - it's a database problem as well since most DBs will not let you insert to multiple tables at one time, so the "first" insert would violate the 1:1 restriction. _That's_ why the EF requirement that one is "principal" exists. – D Stanley Oct 05 '16 at 18:48
  • Reading your answer more closely, you do not have a 1:1 relationship; you have a 1:0..1 relationship that is reciprocal. You could enforce the reciprocity either with a trigger or in your app layer – D Stanley Oct 05 '16 at 18:57

1 Answers1

1

As Gilad points out in the link that EF could not map one-to-one relationship to same table.

However, you can use the follow Code First Fluent API to simulate one-to-one relationship to same table. Under the hood, they behave the same way as you want.

public class Person
{
    public Person()
    {
        Dependents = new List<Person>();
    }

    public int Id { get; set; }
    public string Name { get; set; }
    public int Spouse { get; set; }
    public virtual ICollection<Person> Dependents { get; set; }
    public virtual Person Primary { get; set; }
}

public class PersonMap : EntityTypeConfiguration<Person>
{
    public PersonMap()
    {            
        HasRequired(t => t.Primary)
            .WithMany(t => t.Dependents)
            .HasForeignKey(d => d.Spouse);

    }
}
Community
  • 1
  • 1
Win
  • 61,100
  • 13
  • 102
  • 181