.net-core - EF Core 一对一或零关系

标签 .net-core entity-framework-core ef-core-2.2

我有人员和地址。地址是可选的。 请看下面的代码

class Person
{
    [Key]
    public int PersonID { get; set; }
    public string Name { get; set; }

    public Address Address { get; set; }

}

class Address
{
    [Key, ForeignKey("Person")]
    public int PersonID { get; set; }

    public string City { get; set; }
}

注册码如下:

modelBuilder.Entity<Address>(entity =>
            {
                entity.HasKey(z => z.PersonID);
                entity.HasOne(p => p.Person)
                     .WithOne(a => a.Address)
                     .HasForeignKey<Person>(a => a.PersonID);
            });

我应该如何更改映射以使地址可选?

最佳答案

这里

.HasForeignKey<Person>(a => a.PersonID)

您告诉 EF Person.PersonID 将是 Address 的 FK(外键),即 Person 是依赖的并且正在引用主体地址

应该是相反的:

.HasForeignKey<Address>(a => a.PersonID)

这样,Person(主体)将有 0..1 Address,而 Address(从属)将有 1 Person(因为 PersonId 既是 PK 又是 FK)。

这称为共享主键关联,是在 EF Core 中建模一对零或一对关系的标准(默认)方式。

有关详细信息,请参阅 Relationships .

关于.net-core - EF Core 一对一或零关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54985032/

相关文章:

c# - EF Core 迁移错误 "Could not drop constraint",已在之前的迁移中删除

azure-devops - 如何使用 VSTS 部署运行 EF Core 迁移到 Azure for Web API 项目

postgresql - 如何使用 Entity Framework 核心为 postgres 数据库安装 TimescaleDB 扩展

c# - 如何在 EF core 中添加/更新与实体一端的多对多关系

azure - 如何在启用 EF Core 迁移的情况下在 Azure 中运行蓝绿部署

c# - 表单 View 设计器无法在使用 C# .NET Core 3.1 的 Visual Studio 2019 中工作

c# - 需要帮助将 winform 迁移到 net 5

asp.net-core - 如何在 Linux 上生成大小合理的 .NET Core 进程内存转储文件?

c# - 在 ASP.NET Core Web API 中一起接收文件和其他表单数据(基于边界的请求解析)

sql-server - 基于动态比较查找匹配实体