![](/img/trans.png)
[英]How do I configure one-to-one relationship in EF Core if one of entities does not reference the other one?
[英]ef core one-to-one relationship while keeping keys in both entities
我在应用程序中使用ef core 2.1,并尝试将两个实体之间的关系设置为一对一关系。 同时,我想在两个实体中都保留外键。 假设类如下:
class Principal
{
int Id
int PropA
int PropB
int DependentId
virtual Dependent Dependent
}
class Dependent
{
int Id
int PropC
int PropD
int PrincipalId
virtual Principal Principal
}
并使用像这样的流利的api:
builder.Entity<Principal>()
.HasOne(a => a.Dependent)
.WithOne(b => b.Principal)
.HasForeignKey<Dependent>(c => c.PrincipalId);
在这种情况下Dependent.PrincipalId
是唯一的,但是Principal.DependentId
不是。 我希望两者都是独一无二的。 知道如何实现吗?
在其主键上用ForeignKey属性标记一个表(从属表)。 EF从此推断出一对一:
class Principal
{
int Id
int PropA
int PropB
//int DependentId ----> here
virtual Dependent Dependent
}
class Dependent
{
[ForeignKey("Principal")]
int PrincipalId
//int Id ----> here
int PropC
int PropD
virtual Principal Principal
}
并删除您的fluent api
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.