一对一,没有委托人,并且没有依赖EF? [英] One-to-one without principal and dependent in EF?

查看:87
本文介绍了一对一,没有委托人,并且没有依赖EF?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此问题(关联的主要终点在实体框架中以1:1关系表示什么)的最佳答案是:

In this question (What does principal end of an association means in 1:1 relationship in Entity framework) the best answer says :


在一对一关系中,一端必须是主体,第二端必须是从属的。主体端是首先插入的一端,并且可以不存在从属端而存在。从属端是必须在主体后插入的一端,因为它具有到主体的外键。

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.

我想知道,我怎么能在没有主体和从属元素的实体框架中实现一对一关系?
例如:

I wonder, how can I implement one-to-one relationship in Entity Framework where there are no principal and dependent elements? For example :

public class Person {
    public int Id {get;set;}
    public string Name {get;set;}
    public Person Spouse {get;set;}
}

每个人可能有也可能没有另一人作为配偶。如果必须一对一地满足主体和从属元素的存在,那么,在此Person模型中,主体在哪里,从属在哪里?

Each person may or may not have another one as Spouse. If in one-to-one must sutisfy for the existence of principal and dependent elements, so, where in this Person model principal and where dependent ones?

推荐答案

正如吉拉德(Gilad)在链接

As Gilad points out in the link that EF could not map one-to-one relationship to same table.

但是,您可以使用下面的Code First Fluent API 来模拟与同一表的一对一关系。在内部,它们的行为与您想要的相同。

However, you can use the follow Code First Fluent API to simulate one-to-one relationship to same table. Under the hood, they behave the same way as you want.

public class Person
{
    public Person()
    {
        Dependents = new List<Person>();
    }

    public int Id { get; set; }
    public string Name { get; set; }
    public int Spouse { get; set; }
    public virtual ICollection<Person> Dependents { get; set; }
    public virtual Person Primary { get; set; }
}

public class PersonMap : EntityTypeConfiguration<Person>
{
    public PersonMap()
    {            
        HasRequired(t => t.Primary)
            .WithMany(t => t.Dependents)
            .HasForeignKey(d => d.Spouse);

    }
}

这篇关于一对一,没有委托人,并且没有依赖EF?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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