EF核心一对一或零关系 [英] EF Core One to One or Zero Relationship
问题描述
我有个人和地址。地址是可选的。
请参见以下代码
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);
});
我应该如何更改映射以使Address可选?
How should i change mapping to make Address optionable?
推荐答案
这里
.HasForeignKey<Person>(a => a.PersonId)
您告诉EF Person.PersonId
将是地址
的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)
这样,人员
(委托人)将具有0..1 地址
和地址
(受抚养人)将有1个人员
(因为 PersionId
都是PK和FK)。
This way, Person
(the principal) will have 0..1 Address
, and Address
(the dependent) will have 1 Person
(because the PersionId
is both PK and FK).
这称为共享主键关联,它是对一对一或一个进行建模的标准(默认)方式
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核心一对一或零关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!