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

查看:24
本文介绍了在实体框架中的 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天全站免登陆