ef core - update composite primary key

entity-framework-core multi-tenant

Question

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.

1
1
1/10/2020 2:17:53 PM

Accepted Answer

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.

1
1/10/2020 9:32:55 PM


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