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

后端 未结 3 1084
猫巷女王i
猫巷女王i 2020-11-22 09:33
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         


        
3条回答
  •  抹茶落季
    2020-11-22 10:28

    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()
                .HasOptional(f => f.Boo)
                .WithRequired(s => s.Foo);
    

提交回复
热议问题