In the Entity Framework, what does the primary end of an association indicate in a 1:1 relationship?

c# database-design entity-framework foreign-key-relationship

Question

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;}
}

When I attempted to implement this with Entity Framework, I received the following 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.

Although this mistake has been addressed in queries on StackOverflow, I would still want to know what the word "primary end" really implies.

1
269
2/3/2014 9:53:09 AM

Accepted Answer

One end must be the major end in a one-to-one relationship, while the other end must be dependent. The end that will be put first and may exist independently of the dependent end is known as the principal end. Because it has a foreign key to the principal, the dependent end must be put after the principal.

Since the PK of an entity framework dependency must also be the FK, you should use:

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

Or, proficient mapping

modelBuilder.Entity<Foo>()
            .HasOptional(f => f.Boo)
            .WithRequired(s => s.Foo);
378
6/30/2011 9:00:37 AM

Popular Answer

The [Required] data annotation property may also be used to resolve this:

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

    public Boo Boo { get; set; }
}

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

    [Required]
    public Foo Foo {get; set; }
}

Foo is necessary forBoo .



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow