9

我将 MySQL Connector/Net 6.5.4 与 LINQ to 实体一起使用,我经常得到糟糕的查询性能,因为实体框架生成使用派生表的查询。

这是我多次遇到的简化示例。在 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

如何防止实体框架使用派生表,或者如何说服 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
4

1 回答 1

1

I think your query statement is missing 'select'. You have not identified the record(s) you want. your query:

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

//no select

what are you selecting from the table? try this

example:

var culverCustomers =  from cs in db.CustomerSummaries 
                        where cs.Street == "Culver"
                        select cs;
于 2014-07-08T17:52:34.860 回答