Note that there are some explanatory texts on larger screens.

plurals
  1. POEntity Framework is slow because of derived tables
    primarykey
    data
    text
    <p>I am using MySQL Connector/Net 6.5.4 with LINQ to entities, and I frequently get terrible query performance because the entity framework generates queries that use derived tables.</p> <p>Here is a simplified example of what I've encountered several times. In C#, I write a query like this:</p> <pre><code>var culverCustomers = from cs in db.CustomerSummaries where cs.Street == "Culver" select cs; // later... var sortedCustomers = culverCustomers.OrderBy(cs =&gt; cs.Name).ToList(); </code></pre> <p>Instead of generating simple a query like this:</p> <pre><code>SELECT cust.id FROM customer_summary cust WHERE cust.street = "Culver" ORDER BY cust.name </code></pre> <p>The entity framework generates a query with a derived table like this:</p> <pre><code>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 </code></pre> <p>If I explain both queries I get this for the first query:</p> <pre><code>id, select_type, table, type, possible_keys, rows 1, PRIMARY, addr, ALL, PRIMARY, 9 1, PRIMARY, cust, ref, PRIMARY, 4 </code></pre> <p>... and something awful like this for the entity framework query</p> <pre><code>id, select_type, table, type, possible_keys, rows 1, PRIMARY, &lt;derived2&gt;, ALL, 9639 2, DERIVED, addr, ALL, PRIMARY, 9 2, DERIVED, cust, ref, PRIMARY, 4 </code></pre> <p>Note the first row, where MySQL explains that it's scanning <strong>9000+ records</strong>. Because of the derived table, MySQL is creating a temp table and loading every row. (Or so I'm deducing based on articles like this one: <a href="http://www.mysqlperformanceblog.com/2006/08/31/derived-tables-and-views-performance/" rel="nofollow">Derived Tables and Views Performance</a>)</p> <p><strong>How can I prevent the Entity Framework from using a derived table, or how can I convince MySQL to do the obvious optimization for queries like this?</strong></p> <p>For completion, here is the view that is the source for this linq query:</p> <pre><code>create view customer_summary as select cust.id, cust.name, addr.street customers cust join addresses addr on addr.customer_id = cust.id </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload