且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

提高实体框架中的批量插入性能

更新时间:2022-10-16 10:27:05

有几个改进的机会(如果你正在使用 DbContext ):



设置:

  yourContext.Configuration.AutoDetectChangesEnabled = false; 
yourContext.Configuration.ValidateOnSaveEnabled = false;

在100的包中执行 SaveChanges()插入...或者您可以尝试使用1000个项目的包,并查看性能的更改。



由于在所有这些插入过程中,上下文是相同的,它越来越大,您可以每1000个插入重建上下文对象。 var yourContext = new YourContext(); 我认为这是很大的收获。



在导入中进行这种改进我的数据处理,从7分钟到6秒。



实际的数字...在你的情况下不能是100或1000 ...尝试并调整它。


I want to insert 20000 records in a table by entity framework and it takes about 2 min. Is there any way other than using SP to improve its performance. This is my code:

 foreach (Employees item in sequence)
 {
   t = new Employees ();
   t.Text = item.Text;
   dataContext.Employees.AddObject(t);                  
 }
 dataContext.SaveChanges();

There is opportunity for several improvements (if you are using DbContext):

Set:

yourContext.Configuration.AutoDetectChangesEnabled = false;
yourContext.Configuration.ValidateOnSaveEnabled = false;

Do SaveChanges() in packages of 100 inserts... or you can try with packages of 1000 items and see the changes in performance.

Since during all this inserts, the context is the same and it is getting bigger, you can rebuild your context object every 1000 inserts. var yourContext = new YourContext(); I think this is the big gain.

Doing this improvements in an importing data process of mine, took it from 7 minutes to 6 seconds.

The actual numbers... could not be 100 or 1000 in your case... try it and tweak it.