C# Entity FrameWork MySQL 慢查询 Count()
问题:C# Entity FrameWork MySQL 慢查询 Count() 我在使用 MySQL 和 Entity Framework 4.0 时遇到了严重问题。我已经将一个表放到 EF 设计器表面上,一切看起来都还不错。但是,当我以下列方式执行查询时: using(entityContext dc = new entityContext()) { int numRows = dc.myTa
问题:C# Entity FrameWork MySQL 慢查询 Count()
我在使用 MySQL 和 Entity Framework 4.0 时遇到了严重问题。我已经将一个表放到 EF 设计器表面上,一切看起来都还不错。但是,当我以下列方式执行查询时:
using(entityContext dc = new entityContext()) {
int numRows = dc.myTable.Count();
}
生成的查询如下所示:
SELECT `GroupBy1`.`A1` AS `C1`
FROM (SELECT Count(1) AS `A1`
FROM (SELECT `pricing table`.`a`,
`pricing table`.`b`,
`pricing table`.`c`,
`pricing table`.`d`,
`pricing table`.`e`,
`pricing table`.`f`,
`pricing table`.`g`,
`pricing table`.`h`,
`pricing table`.`i`
FROM `pricing table` AS `pricing table`) AS `Extent1`) AS `GroupBy1`
显而易见,这是一个极其未优化的查询。它正在选择每一行!这不是最优的,此时我什至不可能使用 MySQL + EF。
我已经尝试了 MySQL 6.3.1 [安装起来很有趣] 和 DevArt 的 dotConnect for MySQL 并且都产生了相同的结果。该表有 150 万条记录。执行需要 6-11 秒!
我究竟做错了什么 ?有什么办法可以优化这个[和其他查询]以产生健全的代码,如:
SELECT COUNT(*) FROM table
?
使用 SQLServer 生成相同的查询几乎不需要任何时间,并且会生成合理的代码。
帮助!
编辑:我还想指出,我切换到 DevArt dotConnect MySQL LINQ to SQL 驱动程序,使用 L2S over EF 快 1000000 倍。这也包括查询。
在 EF 中选择 anything 似乎会产生完全疯狂的查询。
dc.pricing_table.OrderBy(j => j.a).Skip(100).Take(100).ToList();
SELECT `Extent1`.`a`,
`Extent1`.`b`,
`Extent1`.`c`,
`Extent1`.`d`,
`Extent1`.`e`,
`Extent1`.`f`,
`Extent1`.`g`,
`Extent1`.`h`,
`Extent1`.`i`
FROM (SELECT `pricing table `.`a`,
`pricing table `.`b`,
`pricing table `.`c`,
`pricing table `.`d`,
`pricing table `.`e`,
`pricing table `.`f`,
`pricing table `.`g`,
`pricing table `.`h`,
`pricing table `.`i`
FROM `pricing table ` AS `pricing table`) AS `Extent1`
ORDER BY `a` ASC
LIMIT 100,100
同样,一个完全错误的查询。 LIMIT 100,100 绝对是在错误的地方。当然,这对我根本不起作用。
解答
该问题可能与您的 .edmx 或 .edml 文件中有定义查询有关。
如果您有 View,或者您的表没有定义主键,Designer 会经常生成 DefiningQuery。请检查模型的 XML 代码并删除 DefiningQuery,以防它存在但不必要。
更多推荐
所有评论(0)