Entity Framework Core and One-to-One Relation: Duplicate entry

.net ef-core-2.0 ef-core-2.1 entity-framework entity-framework-core

Question

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?

1
0
9/9/2018 10:10:11 AM

Accepted Answer

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)

2
9/17/2018 9:28:49 PM

Popular Answer

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 ownerIdand then update the required row.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow