实体框架核心批量扩展:BulkInsertOrUpdate

时间:2021-02-08 14:27:30

标签: c# entity-framework-core

我对 entityfremawork 核心批量扩展功能有要求。 当我们使用 _context.BulkInsertOrUpdate(Customers); 我没有在 sql 客户表上创建任何主键。所以我试图在外部映射目标列(插入或更新) 下面

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

ef core 批量扩展有什么办法

2 个答案:

答案 0 :(得分:0)

如果库不支持这种匹配,则没有解决方案。所以考虑更换第三方库或者等待功能实现。

顺便说一句,我已经在 linq2dbEF Core linq2db.EntityFrameworkCore 之间建立了这座桥梁,所以如果你没有其他选择,这个应该可行。

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

检查 InsertWhenNotMatchedUpdateWhenMatched 的重载 - 在这里,您甚至可以根据目标表中的值自定义应插入或更新哪些字段。

答案 1 :(得分:0)

免责声明:我是 Entity Framework Extensions

的所有者

这个库不是免费的,但很容易涵盖自定义键等场景。 InsertOrUpdate 相当于 BulkMerge

示例:

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

这是一个在线示例:https://dotnetfiddle.net/Lzbh2H