为什么在循环中引用DbSet.Local慢? [英] Why is referencing DbSet.Local slow in a loop?

查看:223
本文介绍了为什么在循环中引用DbSet.Local慢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有sqlite数据库的Entity-Framework 6.1.3。
在页面加载期间,我正在初始化一个循环中的一些属性(见下文)。

I'm using Entity-Framework 6.1.3 with a sqlite database. During page load I'm initializing some properties in a loop (see below).

foreach (var trade in model.Trades)
{
    trade.ExchangeRates = Db.ExchangeRates.Local;
    trade.BaseCurrency = Prj_TradAc.Properties.Settings.Default.BaseCurrency;
}

Db.ExchangeRates.Local从未打到预期的数据库。
所以我期望只为Db.ExchangeRates.Local分配一个应该是快的引用。
然而,只有〜500个交易,循环需要将近10秒!

Db.ExchangeRates.Local never hits the Database which is expected. So I was expecting to only assign a reference to Db.ExchangeRates.Local which should be fast. However with only ~500 Trades the loop takes almost 10s!

当我执行以下

var ers = Db.ExchangeRates.Local;
foreach (var trade in model.Trades)
{
    trade.ExchangeRates = ers;
    trade.BaseCurrency = Prj_TradAc.Properties.Settings.Default.BaseCurrency;
}

相同数据量的相同循环需要〜40ms

the same loop with the same amount of data takes ~40ms

那么为什么访问DBSet.Local这么慢?

So why is accessing DBSet.Local so slow?

编辑:

Db.Configuration.AutoDetectChangesEnable = false

作业快。但是我仍然不明白为什么这是一个问题。我分配的属性只是链接到字段 - 所以这里没有操作。

also makes the assignment fast. However I still do not understand why this is an issue here. My properties which I'm assigning to are just linked to fields - so no operation is going on here. There shouldn't be a change to the DBSet during assignment.

推荐答案

无论何时访问 本地属性(使用属性getter)和 DbContext.Configuration.AutoDetectChangesEnabled 属性为 true (默认情况下),EF调用 ObjectContext.DetectChanges 方法,减慢进程。

Anytime you access Local property (using the property getter), and DbContext.Configuration.AutoDetectChangesEnabled property is true (by default), EF calls ObjectContext.DetectChanges method which slows down the process.

这篇关于为什么在循环中引用DbSet.Local慢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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