how to DbContextBulkExtensions.BulkUpdate with ConcurrencyCheck

48 views Asked by At

I have situation when I have 2 pods that getting requests to update status of object lets call him user, he have 3 statuses : new, verified and failed. they getting in parallel the entity with status new. they are updating the user status one to failed and one to verified. im using to bulkUpdate of DbContextBulkExtensions to update many users. I want that this case will throw me exception.

I saw there is soultion of ConcurrencyCheck attribute in c# data annotation and it working on regular update - but in DbContextBulkExtensions.bulkUpdate its not working. anyone know how to make that work in bulkUpdate?

1

There are 1 answers

1
Timz95 On

According to the README, EFCore.BulkExtensions is able to do concurrency checks on the timestamp of each row. To enable, you can pass a BulkConfig-object with DoNotUpdateIfTimeStampChanged = true to dbContext.BulkUpdate. Non-updated entities are returned to BulkConfig.TimeStampInfo.

A possible example for your case:

var bulkConfig = new BulkConfig() { DoNotUpdateIfTimeStampChanged = true };
await fooContext.BulkUpdateAsync(new Foo[] { new() { Id = 1, Bar = "Foo" }, new() { Id = 2, Bar = "Bar" } },
    bulkConfig);

// Checks if any entities are skipped due to concurrency conflict.
if (bulkConfig.TimeStampInfo != null && bulkConfig.TimeStampInfo.NumberOfSkippedForUpdate > 0)
{
    throw new DBConcurrencyException("<your message here>");
}

... or as pattern

var bulkConfig = new BulkConfig() { DoNotUpdateIfTimeStampChanged = true };
await fooContext.BulkUpdateAsync(new Foo[] { new() { Id = 1, Bar = "Foo" }, new() { Id = 2, Bar = "Bar" } },
    bulkConfig);

// Checks if any entities are skipped due to concurrency conflict.
if (bulkConfig.TimeStampInfo is { NumberOfSkippedForUpdate: > 0 })
{
    throw new DBConcurrencyException("<your message here>");
}