问题描述
基本上,我一个事务中插入35000对象:
Basically, I insert 35000 objects within one transaction:
using(var uow = new MyContext()){
for(int i = 1; i < 35000; i++) {
var o = new MyObject()...;
uow.MySet.Add(o);
}
uow.SaveChanges();
}
这永远需要!
如果我使用的基本 ObjectContex
T(通过使用 IObjectAdapter
),它仍然缓慢,但需要大约20秒。它看起来像 DbSet&LT;&GT;
做一些线性搜索,这需要多长的时间...
This takes forever!If I use the underlying ObjectContex
t (by using IObjectAdapter
), it's still slow but takes around 20s. It looks like DbSet<>
is doing some linear searches, which takes square amount of time...
其他任何人看到这个问题?
Anyone else seeing this problem?
推荐答案
由于已经拉吉斯拉夫在评论所指出的,你需要禁用自动变化检测,以提高性能:
As already indicated by Ladislav in the comment, you need to disable automatic change detection to improve performance:
context.Configuration.AutoDetectChangesEnabled = false;
这变化检测是默认的的DbContext
API中启用。
This change detection is enabled by default in the DbContext
API.
为什么的DbContext
的行为与的ObjectContext
API如此不同的原因是,<$ C的更多功能$ C>的DbContext API将调用 DetectChanges
的ObjectContext API函数内部>自动时变化检测已启用。
The reason why DbContext
behaves so different to the ObjectContext
API is that many more functions of the DbContext
API will call DetectChanges
internally than functions of the ObjectContext
API when automatic change detection is enabled.
Here你可以找到的那些称之为 DetectChanges
默认功能的列表。它们是:
Here you can find a list of those functions which call DetectChanges
by default. They are:
- 的
添加
,连接
,查找
,本地
或删除
的成员DbSet
- 的
GetValidationErrors
,输入
或的SaveChanges
成员在的DbContext
- 在
项
方法DbChangeTracker
- The
Add
,Attach
,Find
,Local
, orRemove
members onDbSet
- The
GetValidationErrors
,Entry
, orSaveChanges
members onDbContext
- The
Entries
method onDbChangeTracker
尤其添加
通话 DetectChanges
负责您遇到的糟糕表现。
Especially Add
calls DetectChanges
which is responsible for the poor performance you experienced.
我此相反的的ObjectContext
API调用 DetectChanges
仅在自动的SaveChanges
,但不是在 ADDOBJECT
和上述其他相应的方法。这就是为什么在默认性能的ObjectContext
更快。
I contrast to this the ObjectContext
API calls DetectChanges
only automatically in SaveChanges
but not in AddObject
and the other corresponding methods mentioned above. That's the reason why the default performance of ObjectContext
is faster.
他们为什么要引进这么多的功能在的DbContext
这个默认的自动变化检测?我不知道,但似乎禁用它,并呼吁 DetectChanges
手动在适当的点被认为是的。
Why did they introduce this default automatic change detection in DbContext
in so many functions? I am not sure, but is seems that disabling it and calling DetectChanges
manually at the proper points is considered as advanced and can easily introduce subtle bugs into your application so use [it] with care.
这篇关于为什么在插入EF 4.1实体如此缓慢相比,ObjectContext的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!