在实体框架中的 1:1 关系中,关联的主体端是什么意思 [英] What does principal end of an association means in 1:1 relationship in Entity framework

查看:18
本文介绍了在实体框架中的 1:1 关系中,关联的主体端是什么意思的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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:

无法确定类型之间关联的主体端ConsoleApplication5.Boo"和ConsoleApplication5.Foo".此关联的主体端必须使用以下任一方法显式配置关系流式 API 或数据注释.

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.

我在 StackOverflow 上看到了有关此错误的解决方案的问题,但我想了解主体端"一词的含义.

推荐答案

在一对一关系中,一端必须是主体,另一端必须是依赖.主端是最先插入的端,它可以在没有依赖端的情况下存在.依赖端是必须插入到主体之后的一端,因为它具有到主体的外键.

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.

如果实体框架 FK 依赖也必须是它的 PK 所以在你的情况下你应该使用:

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

或者流畅的映射

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

这篇关于在实体框架中的 1:1 关系中,关联的主体端是什么意思的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆