Primary key generation processing without identification

Currently, we have tables that do not have an identifier for the primary key. It would be too expensive to change this due to interoperability.

I am thinking of handling an ObjectContext SavingChanges event to set its values.

(pseudo code)

void SavingChanges(context) { foreach (var entity in context) { if (entity.HasIdentity) continue; entity.PrimaryKey = GetNextPrimaryKey(entity.Type); } } 

I can only think of using a separate connection for this. And yes, GetNextPrimaryKey would be optimized to reduce the number of rounds, but I think it was enough to explain the general idea.

Will this work? Should I try something else?

+4
source share
1 answer

It depends on the logic in the GetNextPrimaryKey method.

If your method is executed in several threads, then you will have a chance that the same key will be assigned to several objects.

But if your GetNextPrimaryKey promotes your key and always returns a new key, whether it is used or not, then there is no problem.

But if your logic is simply to find out the last key used and make the key + 1, then in multi-threaded situations or in web applications there will be conflicts.

It would be best to use some kind of stored procedure and always return a new key from SP, so there would be no problem if GetNextPrimaryKey is executed in parallel.

0
source

Source: https://habr.com/ru/post/1340956/


All Articles