EFCore.BulkExtensions How to update records on condition?

1k views Asked by At

I am using EFCore.BulkExtensions for insert and update records in a table. But I have a problem with update records on condition.

For example, I have 15 records (10 to insert, 5 to update). I need to insert 10, but update only 2, because 3 records have old value in UpdatedAt property (database contains more recent data).

If I use EFCore.BulkExtensions like this:

_dbContext.BulkInsertOrUpdateAsync(entitiesList, _bulkConfig);

10 records will be inserted and 5 records will be updated. So the data in the database will be updated by older ones.

To solve my problem I want something like this:

_dbContext.BulkInsertOrUpdateAsync(entitiesList, _bulkConfig,
    (oldRecord, newRecord) => newRecord.UpdatedAt > oldRecord.UpdatedAt);

Can you suggest some efficient way to solve this problem with EFCore.BulkExtensions?

1

There are 1 answers

10
Svyatoslav Danyliv On

This is not direct answer for EFCore.BulkExtensions, but alternative how to do that with linq2db.EntityFrameworkCore. Note that I'm one of the creators.

await context.SomeTable
    .ToLinqToDBTable()
    .Merge()
    .Using(entitiesList)
    .On((t, s) => t.Id == s.Id)
    .InsertWhenNotMatched()
    .UpdateWhenMatchedAnd((t, s) => s.UpdatedAt > t.UpdatedAt)
    .MergeAsync();

Select appropriate package 2.x for EF Core 2.x, 3.x for EF Core 3.1.x, etc.