#1
An application cannot change the primary key (PK) of an existing
(already saved) entity.
It makes no difference whether
the PK is composite or single valued … you just can’t do it.
My recollection is that EF
prohibits changes to the PK but I’m not certain. We do know that allowing a
change to the PK invites numerous unfortunate consequences when the PK of the
changed entity is the foreign key of other, child entities. Consider the
effect on Order-Line-items of changing the ID of its parent Order. The database
could detect a FK violation and throw an exception; it might not in which case
you’ve orphaned the child line items.
We agree that DF does not
properly report the error when the application tries to change the PK
DF
defect #1: We should throw a clear exception when you try to save an updated
entity with a pending change to the PK. Instead, the save appears to succeed
although it did not.
DF
defect #2: We do throw an exception if you try to save an updated entity with a
pending change to the PK and at least one other property. Unfortunately, (a) we
rely on the server to produce the exception when we could detect it on the
client and (b) the wording of the exception is not clear about the cause or the
resolution.
We will correct these defects in
our next release. But our no-PK-change rule is a deliberate choice in DF; we
feel the defects are in the reporting, not in the prohibition itself.
What to do?
All architects agree that one
should never change the primary key of an existing entity. That said, we know
that it happens, especially with legacy databases in which the key contains a
meaningful value … such as some portion of an entity’s “name”.
If the app must be able to
change the entity PK, the only permitted way to do that is
·
copy the entity,
·
give it the revised
PK,
·
delete the original.
You can do this all in the same
EntityManager and submit these changes in the same save (so they are committed
in the same transaction).
This insert+delete approach is
open to the same risks as I mentioned above: potential FK violations and
orphaned children. But at least you had to work at “doing the wrong thing”.