Search code examples
entity-framework-coremulti-tenant

ef core - update composite primary key


I have several tables with composite key { Id + OrgId }. Id is provided by the user of the application, OrgId is handled by the system. I would like to set OrgId for all instances of these tables, without having to go to each repo then set OrgId manually before attaching.

How can I do this?

In the case where OrgId is not part of the primary key, I overrid SaveChanges() to update all tracked entities having OrgId before calling the base implementation. This approach does not work when OrgId is part of the primary key because we cannot update primary key of an entity once it is tracked.


Solution

  • So inside the SaveChanges() override I set entry.Entity.OrgId, entry.OriginalValues["OrgId"], and entry.CurrentValues["OrgId"] with the same value. I no longer get the exception. Also, at this stage I made sure to mark OrgId as .ValueGeneratedNever().

    Although, I would recommend taking a look at @IvanStoev's solution.