由于派生表,实体框架很慢

时间:2012-11-02 18:29:30

标签: c# mysql entity-framework linq-to-entities database-performance

我正在使用带有LINQ实体的MySQL Connector / Net 6.5.4,并且我经常会遇到糟糕的查询性能,因为实体框架会生成使用派生表的查询。

这是我多次遇到的简化示例。在C#中,我写了一个这样的查询:

var culverCustomers = from cs in db.CustomerSummaries where cs.Street == "Culver" select cs;
// later...
var sortedCustomers = culverCustomers.OrderBy(cs => cs.Name).ToList();

而不是像这样生成简单的查询:

SELECT cust.id FROM customer_summary cust WHERE cust.street = "Culver" ORDER BY cust.name

实体框架使用派生表生成一个查询,如下所示:

SELECT Project1.id FROM (
    SELECT cust.id, cust.name, cust.street FROM customer_summary cust
    WHERE Project1.street = "Culver"
) AS Project1 -- here is where the EF generates a pointless derived table
ORDER BY Project1.name

如果我解释两个查询,我会在第一个查询中得到这个:

id, select_type, table, type, possible_keys, rows
1,  PRIMARY,     addr,  ALL,  PRIMARY,       9
1,  PRIMARY,     cust,  ref,  PRIMARY,       4

......对于实体框架查询而言,这样的事情很糟糕

id, select_type, table,      type, possible_keys, rows
1,  PRIMARY,     <derived2>, ALL,                 9639
2,  DERIVED,     addr,       ALL,  PRIMARY,       9
2,  DERIVED,     cust,       ref,  PRIMARY,       4

请注意第一行,其中MySQL解释说它正在扫描 9000+条记录。由于派生表,MySQL正在创建临时表并加载每一行。 (或者我根据这样的文章推断:Derived Tables and Views Performance

如何阻止Entity Framework使用派生表,或者如何说服MySQL对此类查询进行明显的优化?

为了完成,以下是该linq查询的源视图:

create view  customer_summary as
select cust.id, cust.name, addr.street
customers cust 
join addresses addr
on addr.customer_id = cust.id

1 个答案:

答案 0 :(得分:1)

我认为您的查询语句缺失了&#39; select&#39;。您尚未确定所需的记录。  您的查询:

var culverCustomers = from cs in db.CustomerSummaries 
                        where cs.Street == "Culver";

//没有选择

你从桌子上选择什么?试试这个

示例:

var culverCustomers =  from cs in db.CustomerSummaries 
                        where cs.Street == "Culver"
                        select cs;