简体   繁体   English

一对一没有委托人,依赖EF?

[英]One-to-one without principal and dependent in EF?

In this question (What does principal end of an association means in 1:1 relationship in Entity framework) the best answer says : 在这个问题中 (关联的主要结束在实体框架中以1:1的关系表示什么)最佳答案是:

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? 我想知道,我如何在Entity Framework中实现一对一关系,其中没有主要元素和依赖元素? For example : 例如 :

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

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? 如果一对一必须满足主要和从属元素的存在,那么,在这个Person模型主体和依赖元素的位置?

As Gilad points out in the link that EF could not map one-to-one relationship to same table. 正如吉拉德在链接中指出的那样,EF无法将一对一的关系映射到同一个桌面。

However, you can use the follow Code First Fluent API to simulate one-to-one relationship to same table. 但是,您可以使用以下Code First Fluent API来模拟与同一个表的一对一关系。 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);

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM