【发布时间】:2014-09-11 02:27:50
【问题描述】:
在分页 Product 对象列表时,我遇到了 Entity Framework 和 Linq 的性能问题:
var data =_service.GetAll();
var page = data.Skip((index) * pageSize).Take(pageSize);
list.Add(page.AsEnumerable); // ** its slow right here
我的测试数据库中有 1958 个产品,但是当上面的代码运行时,我可以看到执行了 3916 个(即 1958 *2)个单独的查询(通过查看 sql profiler)。
Product 类看起来像:
public class Product
{
public virtual int Id {get;set;}
public virtual string ProductCode {get;set;}
//..etc other properties
public virtual ICollection<WarehouseProduct> WarehouseProducts { // etc }
public virtual ICollection<InvoiceLine> InvoiceLines { // etc }
// etc other navigation properties
}
在 sql profiler 中我可以看到这个查询执行了 3916 次:
SELECT
[Extent1].[Id] AS [Id],
[Extent1].[ProductId] AS [ProductId],
// etc
FROM [dbo].[WarehouseProducts] AS [Extent1]
我做错了什么? Product 对象有 12 个不同的导航属性,但只有 WarehouseProduct 被查询了 3916 次。请注意,该查询没有 WHERE 子句,但两个表之间存在外键关系(这就是它是导航属性的原因)
【问题讨论】:
-
你确定它执行了两次,而且你不只是在看BeginExec/EndExec形式的重复行吗?
-
谢谢,您是正确的 - 它在配置文件中显示 SQL:BatchStarting 和 SQL:BatchEnding,因此它是 1958 次查询。但这仍然不能解释为什么它对每个产品都执行一次,并且没有任何 where 子句。
-
能把GetAll方法的代码贴出来吗?
-
是的,真的很难判断黑盒子内的实际查询发生了什么。
-
service.GetAll()调用repository.GetAll(),这只是return ObjectSet.AsQueryable();
标签: c# linq performance entity-framework