实体框架 - 表现在计数 [英] Entity Framework - Performance in count
问题描述
我已经对实体框架的性能一个小问题。
I've a little question about performance with Entity Framework.
类似
using (MyContext context = new MyContext())
{
Document DocObject = context.Document.Find(_id);
int GroupCount = context.Document.Where(w=>w.Group == DocObject.Group).ToList().Count();
}
大约需要2秒,我的数据库(约30K的数据集),而这一个
takes about 2 seconds in my database (about 30k datasets), while this one
using (MyContext context = new MyContext())
{
Document DocObject = context.Document.Find(_id);
int GroupCount = context.Document.Where(w=>w.Group == DocObject.Group).Count();
}
需要0.02秒。
takes 0,02 seconds.
当我的10个文件过滤器具有20秒的等待,我检查了我的代码,并改变了这种不使用了ToList()
在计数()
。
When my filter for 10 documents had 20 seconds to wait, I checked my code, and changed this to not use ToList()
before Count()
.
为什么需要2秒与了ToList这一行()
?
推荐答案
调用了ToList()
然后计数()
将:
- 执行整个
从WHERE
对数据库 - 然后兑现全部所得实体为.NET对象
- 创建一个新的
列表< T>
对象包含所有结果 - 返回
计数
您刚才创建的列表净财产 $结果b $ b
- execute the whole
SELECT FROM WHERE
against your database - then materialize all the resulting entities as .Net objects
- create a new
List<T>
object containing all the results - return the result of the
Count
property of the .Net list you just created
调用计数()
针对的IQueryable
将:
- 执行
SELECT COUNT从那里
对数据库 - 返回
的Int32
与行数
- execute
SELECT COUNT FROM WHERE
against your database - return an
Int32
with the number of rows
显然,如果你只是对项目的数量(不是项目本身),那么你不应该调用过兴趣了ToList()
第一,因为它需要什么了大量的资源。
Obviously, if you're only interested in the number of items (not the items themselves), then you shouldn't ever call ToList()
first, as it will require a lot of resources for nothing.
这篇关于实体框架 - 表现在计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!