简体   繁体   English

EF 7 (Beta 7) 一对一关系

[英]EF 7 (Beta 7) One-to-One Relationship

I've noticed questions that have answered this problem for earlier beta versions of EF 7 (like here ), but I haven't seen it solved for Beta 7, so here it goes:我注意到一些问题已经为 EF 7 的早期测试版(如这里)回答了这个问题,但我还没有看到它为 Beta 7 解决,所以这里是:

I have 2 entities, simplified as follows:我有 2 个实体,简化如下:

public class FirstEntity
{
    public int FirstEntityID { get; set; }
    /*
        Other fields here
    */
    public int? SecondEntityID { get; set; }
    public SecondEntity SecondEntityProperty { get; set; }
}

public class SecondEntity
{
    public int FirstEntityID { get; set; } 
    /*
        Other fields here
    */
    public FirstEntity FirstEntityProperty { get; set; }
}

The way to map everything has changed so much from earlier versions.映射所有内容的方式与早期版本相比发生了很大变化。 How do I map these two entities in a One-to-One relationship?如何在一对一关系中映射这两个实体?

It has been changed for EF7 rc1-final.它已针对 EF7 rc1-final 进行了更改。

modelBuilder.Entity<FirstEntity>()
            .HasOne(q => q.SecondEntity)
            .WithMany()
            .HasForeignKey(q => q.SecondEntityID);

upd:更新:

modelBuilder.Entity<FirstEntity>()
            .HasOne(q => q.SecondEntity)
            .WithOne(v => v.FirstEntity)
            .HasForeignKey<FirstEntity>(q => q.SecondEntityID);

Beta 7 relies heavily on using the Reference method of the Fluent API in order to do any kind of Foreign Key relationship, which has you first select the navigation property involved in the FK relationship. Beta 7 在很大程度上依赖于使用 Fluent API 的Reference方法来处理任何类型的外键关系,这需要您首先选择 FK 关系中涉及的导航属性。 Then, since this is a One-to-One relationship, you use the InverseReference relationship to specify which navigation property on the other side of the relationship this would apply to.然后,由于这是一对一关系,因此您可以使用InverseReference关系指定这将应用于关系另一侧的哪个导航属性。 Only then can you actually start to specify the keys involved, using the ForeignKey and PrincipalKey methods.只有这样,您才能真正开始使用ForeignKeyPrincipalKey方法指定所涉及的键。

All told, here's the solution that I used:总而言之,这是我使用的解决方案:

modelBuilder.Entity<SecondEntity>
    .Reference(s => s.FirstEntity)
    .InverseReference(f => f.SecondEntity)
    .ForeignKey(typeof(SecondEntity), "FirstEntityID")
    .PrincipalKey(typeof(FirstEntity), "SecondEntityID");

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

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