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

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

问题描述

在我的.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,而Address实体使用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; }
}

您不需要 ForeignKey 属性在 PID 属性上再也没有,因为这种关系配置很流畅。此外,您的代码还会产生编译器错误,因为类不能具有相同名称的成员。因此,我添加了 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天全站免登陆