There's One-to-One relationship:
builder.Entity<Models.Card>()
.HasOne<Models.Owner>()
.WithOne(c => c.Card)
.HasForeignKey<Models.Owner>("OwnerId");
At this moment
OwnerId = 1 has Card.Id = 333
and
OwnerId = 2 has Card.Id = 444
If try to change CardId for OwnerId = 1
to CardId = 444
I'll get an error like Duplicate entry ... for key ...
, because OwnerId = 2 already has the same Card (Card.Id = 444).
What is the best way to prevent this behavior: to remove Card.Id = 444 from OwnerId = 2 and change CardId to requested for Owner 1?
yes; 1:1 is enforced via unique FK on one side, so the Owner.CardId
property for OwnerId = 2
must first be changed to a different value (or that Owner
record deleted).
Unless both sides of the relationship are optional (i.e. an Owner
doesn't have to have a Card
and a Card
doesn't have to have an Owner
), a shared primary key should be used (the optional side of the 1:? relationship's PK should also be a FK to the requried side's PK)
First set the CardId
for OwnerId
to null (if this can be made as null
), but again it will give you duplicate key if any other row has null
value. So you have to delete the row for this ownerId
and then update the required row.