Why does EntityFramework do SELECT a,b,c FROM (SELECT a,b,c FROM MyView)?

爱⌒轻易说出口 提交于 2019-12-12 02:23:39

问题


I followed the tutorial here to auto-generate my POCO classes from an existing MySQL database. The generated POCO classes worked as expected for all of my MySQL table objects. The database also has a fairly complex, legacy MySQL view that references 8 tables using both INNER and LEFT OUTER joins. The view itself is fine and there's no issue when tested in MySQL workbench. However, when I tried to select a few records using the auto-generated POCO class for the view, the operation timed out even though its (hand written) equivalent SQL statement worked perfectly well and returned the desired records really fast as expected. So I enabled logging in MySQL to inspect what was happening behind the scenes and it turned out that the EF generated SQL was somewhat different from what I expected it to be.

My hand written version was:

select a, b, c from MyView where a = 1   /* 'a' is a primary key on one of the underlying tables */

However, the EF generated version was:

select Extent1.a, Extent1.b, Extent1.c from (select a, b, c from MyView) as Extent1 where Extent1.a = 1

This explained why I was getting a timeout because MyView has almost 1 million rows. However, I'm still wondering 1) why EF would issue such an ineffective query, and 2) how I should fix this.

I'm using VisualStudio 2010 (can't upgrade to 2012 at this time), .NET Framework 4.0, EF 4.0 & EF 5.x DbContext Generator for C# (as suggested in the above tutorial)

来源:https://stackoverflow.com/questions/14177424/why-does-entityframework-do-select-a-b-c-from-select-a-b-c-from-myview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!