本文介绍了使用EntityFramework Extended批量插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据



为什么?

解决方案

AddRange



添加范围不会执行BulkInsert ,将所有实体都添加到集合中之后,它只需检测一次。



DetectChange方法可能非常慢。



请参阅:



正如您所注意到的,它可以将实体一个接一个地保存在数据库中,这非常慢。



EF.Extended



不再支持此库,并且没有批量插入功能。



批量插入库



以下三个主要库支持批量插入:




  • 已付费但受支持

  • 不再受支持

  • 不再受支持



请注意,两个免费库都不支持所有继承和关联。






免责声明:我是该项目的所有者



除了批量插入之外,该库还允许您执行所有批量操作:




  • BulkSaveChanges

  • BulkInsert

  • BulkUpdate

  • BulkDelete

  • BulkMerge

  • BulkSynchronize



示例:

  //易于使用的
context.BulkSaveChanges();

//易于自定义
上下文。BulkSaveChanges(bulk => bulk.BatchSize = 100);

//执行批量操作
context.BulkDelete(customers);
context.BulkInsert(customers);
context.BulkUpdate(customers);

//自定义主键
上下文。BulkMerge(customers,operation => {
operation.ColumnPrimaryKeyExpression =
customer => customer.Code;
});


According to this, bulk insert in Entity can be made using the following code:

 var customers = GetCustomers();   
 db.Customers.AddRange(customers);   
 db.SaveChanges();  

I used SQL Profiler to verify how many insert queries were executed and I saw there was an insert for each element of the list.

Why?

解决方案

AddRange

Add range doesn't perform a BulkInsert, it simply DetectChanges once after all entities are added to the set.

The DetectChange method can be VERY slow.

See: Entity Framework - DetectChanges Performance

As you noticed, it saves entities one by one in the database which is INSANELY slow.

EF.Extended

This library is not longer supported, and there is no Bulk Insert feature.

Bulk Insert Library

There is three major library supporting Bulk Insert:

Be careful, both free libraries don't support all inheritances and associations.


Disclaimer: I'm the owner of the project Entity Framework Extensions

In addition of Bulk Insert, this library allows you to perform all bulk operations:

  • BulkSaveChanges
  • BulkInsert
  • BulkUpdate
  • BulkDelete
  • BulkMerge
  • BulkSynchronize

Example:

// Easy to use
context.BulkSaveChanges();

// Easy to customize
context.BulkSaveChanges(bulk => bulk.BatchSize = 100);

// Perform Bulk Operations
context.BulkDelete(customers);
context.BulkInsert(customers);
context.BulkUpdate(customers);

// Customize Primary Key
context.BulkMerge(customers, operation => {
   operation.ColumnPrimaryKeyExpression = 
        customer => customer.Code;
});

这篇关于使用EntityFramework Extended批量插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 13:31