C# – What does principal end of an association means in 1:1 relationship in Entity framework

cdatabase-designentity-frameworkforeign-key-relationship

public class Foo
{
    public string FooId{get;set;}
    public Boo Boo{get;set;}
}


public class Boo
{
    public string BooId{get;set;}
    public Foo Foo{get;set;}
}

I was trying to do this in Entity Framework when I got the error:

Unable to determine the principal end of an association between the types
'ConsoleApplication5.Boo' and 'ConsoleApplication5.Foo'.
The principal end of this association must be explicitly configured using either the
relationship fluent API or data annotations.

I have seen questions on StackOverflow with a solution for this error, but I want to understand what the term "principal end" means.

Best Answer

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.

In case of entity framework FK in dependent must also be its PK so in your case you should use:

public class Boo
{
    [Key, ForeignKey("Foo")]
    public string BooId{get;set;}
    public Foo Foo{get;set;}
}

Or fluent mapping

modelBuilder.Entity<Foo>()
            .HasOptional(f => f.Boo)
            .WithRequired(s => s.Foo);
Related Topic