Reputation: 3762
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. 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:
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. I would like both of them to be unique. Any idea how this can be achieved ?
Upvotes: 0
Views: 56
Reputation: 3113
Mark one of the tables (the dependent table) with the ForeignKey attribute on its Primary Key. EF infers 1-to-1 from this:
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
Upvotes: 2