我正在使用EF 4.4.20627.0
,MySQL 5.6
版本MySQL .net connector
6.6.4
我有一个这样的方法,它生成的 sql 是very very slow
(需要超过 1 分钟)
private List<TNews> GetPagedNews(int pagenum, int pagesize,
AdvSearcherArgs advcArgs, string keyword)
{
var dataSrc = _dbRawDataContext.TNews.Where(x => x.Id>0);
if (!string.IsNullOrWhiteSpace(advcArgs.PMAC))
{
dataSrc = dataSrc.Where(m => m.Pmac == advcArgs.PMAC);
}
if (!string.IsNullOrWhiteSpace(advcArgs.BegineDate))
{
var begin = Convertion.ToDate(advcArgs.BegineDate);
var end = Convertion.ToDate(advcArgs.EndDate);
dataSrc = dataSrc.Where(m => m.PmacDT >=begin && m.PmacDT<end);
}
dataSrc = dataSrc.OrderByDescending(n => n.PmacDT).Skip(pagenum * pagesize).
Take(pagesize);
var cnt = dataSrc.Count();
SetPagerValues(pagenum, pagesize, cnt);
return dataSrc.ToList();
}
生成的sql是这样的:
SELECT
`Project1`.*
FROM
(
SELECT
`Extent1`.*
FROM `tnews` AS `Extent1`
WHERE (`Extent1`.`Id` > 0)
AND ((`Extent1`.`PmacDT` >= '2013-01-01 00:00:00 ') AND
(`Extent1`.`PmacDT` < '2013-01-07 00:00:00 '))
) AS `Project1`
ORDER BY
`Project1`.`PmacDT` DESC LIMIT 0,20
/* Affected rows: 0 Found rows: 20 Warnings: 0 Duration for 1 query: 00:01:30 */
如果我将order by
andlimit
子句移动到大括号中,这个 sql 将是very fast
(成本低于1 sec
):
SELECT
`Project1`.*
FROM
(
SELECT
`Extent1`.*
FROM `tnews` AS `Extent1`
WHERE (`Extent1`.`Id` > 0)
AND ((`Extent1`.`PmacDT` >= '2013-01-01 00:00:00 ') AND
(`Extent1`.`PmacDT` < '2013-01-07 00:00:00 '))
ORDER BY
`PmacDT` DESC LIMIT 0,20
) AS `Project1`
/* Affected rows: 0 Found rows: 20 Warnings: 0 Duration for 1 query: 0.000 sec. */
是什么ProjectX
意思Extent1
?为什么实体框架不把orderby * limit x,y
真正的查询放在外面?
sql很奇怪,肯定会让查询很慢,我永远不会那样写sql...那么如何让EF生成一个CORRECT
sql?
有什么建议么?