实体框架核心配置一对零或具有相同主键的关系 [英] Entity Framework Core Configuration one to zero or one relationship with same primary key

查看:21
本文介绍了实体框架核心配置一对零或具有相同主键的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 .NET MVC 项目中,我的域类具有一对一或零关系:

In my .NET MVC project, I have my domain classes with one to one or zero relationship as:

public class Person
{
    public int Id { get; set; }

    public string FullName { get; set; }

    public Address Address { get; set; }
}

public class Address
{
    public string Address { get; set; }
    public string City { get; set; }

    public virtual Person Person { get; set; }
    [Key, ForeignKey("Person")]
    public int PID { get; set; }
}

这是使用 EF 6.x,地址实体使用 PID(外键)作为其标识列.此代码在 EF 6.x 中自动配置,无需任何显式配置.

This is using EF 6.x and the Address entity uses PID (which is foreign key) as its identity column. This code is automatically configured in EF 6.x without any explicit configuration.

现在,我正在将此解决方案移植到 .NET Core 2.1.在这里,EF Core 不适用于 EF 6.x 的数据注释.例如,我无法获取属性 person.Address.City 看来我需要使用 FluentAPI 手动配置它.

Now, I am porting this solution to .NET Core 2.1. Here, the EF Core doesn't work with the Data Annotations of EF 6.x. I cannot for example get the property person.Address.City It appears I need to configure it manually using FluentAPI.

到目前为止,我已经尝试了三种不同的配置,一个接一个都无济于事:

So far I have tried three different configs, one after another to no avail:

//First config
       modelBuilder.Entity<Person>()
            .HasOne(p => p.Address)
            .WithOne(a => a.Person);

//Second config
        modelBuilder.Entity<Person>()
            .OwnsOne(p => p.Address);

//Third config
        modelBuilder.Entity<Person>()
            .OwnsOne(p => p.Address)
            .OwnsOne(a=>a.Person);

这个项目数据量很大,需要使用现有的实体结构进行配置.请帮忙.

This project has a lot of data and needs to be configured using the existing entity structure. Please help.

推荐答案

你的第一次尝试很接近,你只需要使用 HasForeignKey 方法指定哪个字段是关系的外键:

Your first try was close, you just need to specify which field is the foreign key of the relationship using the HasForeignKey method:

modelBuilder.Entity<Person>()
    .HasOne(p => p.Address)
    .WithOne(a => a.Person)
    .HasForeignKey<Address>(a => a.PID);

为了完整起见:

public class Address
{
    [Column("Address")]
    public string Addr { get; set; }
    public string City { get; set; }

    public virtual Person Person { get; set; }
    [Key]
    public int PID { get; set; }
}

您不再需要 PID 属性上的 ForeignKey 属性,因为此关系已配置流畅.此外,您的代码产生了编译器错误,因为类不能有同名的成员.因此我添加了一个 Column 属性来解决这个问题.

You don't need the ForeignKey attribute on the PID property any more as this relationship is configured fluently. Furthermore, your code produced a compiler error because classes cannot have members of the same name. Hence I added a Column attribute to workaround this problem.

这篇关于实体框架核心配置一对零或具有相同主键的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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