[英]ef core one-to-one relationship while keeping keys in both entities
I am using ef core 2.1 in my application and trying to set up a relation between two entities as one-to-one relationship. 我在应用程序中使用ef core 2.1,并尝试将两个实体之间的关系设置为一对一关系。 At the same time i would like to keep foreign keys in both of my entities. 同时,我想在两个实体中都保留外键。 Let's say classes are like: 假设类如下:
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
}
And with fluent api like: 并使用像这样的流利的api:
builder.Entity<Principal>()
.HasOne(a => a.Dependent)
.WithOne(b => b.Principal)
.HasForeignKey<Dependent>(c => c.PrincipalId);
In this scenario Dependent.PrincipalId
is unique but Principal.DependentId
is not. 在这种情况下Dependent.PrincipalId
是唯一的,但是Principal.DependentId
不是。 I would like both of them to be unique. 我希望两者都是独一无二的。 Any idea how this can be achieved ? 知道如何实现吗?
Mark one of the tables (the dependent table) with the ForeignKey attribute on its Primary Key. 在其主键上用ForeignKey属性标记一个表(从属表)。 EF infers 1-to-1 from this: 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
}
and remove your fluent api
并删除您的fluent api
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.