实体框架性能问题,saveChanges非常慢 [英] Entity framework performance issue, saveChanges is very slow

查看:493
本文介绍了实体框架性能问题,saveChanges非常慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我正在做一些简单的EF工作。非常简单,首先

Recently, I am doing some simple EF work. Very simple, first,

List<Book> books = entity.Books.WHERE(c=>c.processed==false)ToList();  
then  
    foreach(var book in books)  
    {  
      //DoSomelogic, update some properties,   
    book.ISBN = "ISBN " + randomNumber();  
    book.processed = true;  
    entity.saveChanges(book)  
    }  

我放了<$ c $ foreach 中的c> entity.saveChanges ,因为它是一个很大的列表,大约有10万条记录,如果该记录没有问题,则标记将此记录设置为book.processed = true,如果该过程因异常而中断,那么下一次,我不必再次处理这些良好的记录。

I put entity.saveChanges within the foreach because it is a large list, around 100k records, and if this record is processed without problem, then flag this record, set book.processed = true, if the process is interrupted by exception, then next time, I don't have to process these good records again.

一切对我来说似乎还可以。处理数百条记录时速度很快。然后,当我们移至10​​万条记录时,entity.saveChanges非常慢。每条记录大约1-3秒。然后,我们保留实体模型,但将 entity.saveChanges 替换为经典的 SqlHelper.ExecuteNonQuery( update_book,sqlparams) 。而且速度非常快。

Everything seems ok to me. It is fast when you process hundreds of records. Then when we move to 100k records, entity.saveChanges is very very slow. around 1-3 seconds per record. Then we keep the entity model, but replace entity.saveChanges with classic SqlHelper.ExecuteNonQuery("update_book", sqlparams). And it is very fast.

有人可以告诉我为什么实体框架处理这么慢吗?并且,如果我仍然想使用entity.saveChanges,什么是改善性能的最佳方法是什么?

Could anyone tell me why entity framework process that slow? And if I still want to use entity.saveChanges, what is the best way to improve the performance?

谢谢

推荐答案

在执行插入操作之前,请关闭更改跟踪。这将显着提高您的性能(数量级)。将 SaveChanges()放在循环之外也有帮助,但是关闭更改跟踪将有更多帮助。

Turn off change tracking before you perform your inserts. This will improve your performance significantly (magnitudes of order). Putting SaveChanges() outside your loop will help as well, but turning off change tracking will help even more.

using (var context = new CustomerContext())
{
    context.Configuration.AutoDetectChangesEnabled = false;

    // A loop to add all your new entities

    context.SaveChanges();
}

请参见此页面以了解更多信息。

See this page for some more information.

这篇关于实体框架性能问题,saveChanges非常慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆