EF Core 一对一或零关系 [英] EF Core One to One or Zero Relationship

查看:53
本文介绍了EF Core 一对一或零关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have Person and Address. Address is optional. Please see below code

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);
            });

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

How should i change mapping to make Address optionable?

推荐答案

这里

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

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

you are telling EF that Person.PersonId will be a FK (foreign key) to Address, i.e. Person is dependent and is referencing the principal Address.

应该是相反的:

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

这样,Person(主体)将有 0..1 Address,而 Address(依赖者)将有 1 Person(因为 PersonId 既是 PK 又是 FK).

This way, Person (the principal) will have 0..1 Address, and Address (the dependent) will have 1 Person (because the PersonId is both PK and FK).

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

This is called Shared Primary Key association and is the standard (and default) way of modelling one to zero or one relationship in EF Core.

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

For more info, see Relationships.

这篇关于EF Core 一对一或零关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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