user1926055
user1926055

Reputation: 11

Entity Framework core bulk Extensions: BulkInsertOrUpdate

I have requirement in entityfremawork core bulk extensions feature. when we are using _context.BulkInsertOrUpdate(Customers); I have not created any primary key on sql customer table. So i am trying to map target columns(Insert or update) externally like below

context.BulkInsertOrUpdate()
  .MatchTargetOn(x => x.CustomerId)
  .MatchTargetOn(x => x.CustomerName)
  .Commit(db.Database.Connection);

Is there any way in ef core bulk extensions

Upvotes: 1

Views: 3369

Answers (2)

Jonathan Magnan
Jonathan Magnan

Reputation: 11347

Disclaimer: I'm the owner of Entity Framework Extensions

This library is not free but covers easily scenarios such as custom keys. The InsertOrUpdate is equivalent to BulkMerge.

Example:

context.BulkMerge(list,  options => options.ColumnPrimaryKeyExpression = c => 
    new { c.CustomerId, c.CustomerName });

Here is an online example: https://dotnetfiddle.net/Lzbh2H

Upvotes: 0

Svyatoslav Danyliv
Svyatoslav Danyliv

Reputation: 27302

There is no solution if library do not support such matching. So consider to change third party library to another or wait for feature implementation.

BTW, I have created this bridge between linq2db and EF Core linq2db.EntityFrameworkCore, so if you have no other options, this one should work.

context.Customers
   .ToLinqToDBTable()
   .Merge()
   .Using(entities)
   .On((t, s) => t.CustomerId == s.CustomerId || t.CustomerName == s.CustomerName)
   .InsertWhenNotMatched()
   .UpdateWhenMatched()
   .Merge();

Check overloads of InsertWhenNotMatched and UpdateWhenMatched - here you can customize which fields should be inserted or updated even based on values from target table.

Upvotes: 2

Related Questions