Linq 为什么实体框架在生成SQL时会忽略Take()方法?
我正在实体框架中使用.Skip和.Take方法。生成SQL时将执行.Skip调用。答案是否定的。此代码:Linq 为什么实体框架在生成SQL时会忽略Take()方法?,linq,entity-framework,linq-to-entities,Linq,Entity Framework,Linq To Entities,我正在实体框架中使用.Skip和.Take方法。生成SQL时将执行.Skip调用。答案是否定的。此代码: public IList<DocPullRun> GetDocRunsPaginated(int startRowIndex, int maximumRows) { Logger.Debug("GetDocRunsPaginated: startRowIndex: {0}, maximumRows: {1}", startRowIndex, ma
public IList<DocPullRun> GetDocRunsPaginated(int startRowIndex, int maximumRows) {
Logger.Debug("GetDocRunsPaginated: startRowIndex: {0}, maximumRows: {1}", startRowIndex, maximumRows);
Debug.Assert(startRowIndex >= 0);
IOrderedQueryable<DocPullRun> sortedPulls =
from run in DB.DocPullRuns
.Include("DocumentPullDefinition")
.Include("DocumentPullDefinition.Case")
.Include("DocumentPullDefinition.DocCategory")
.Include("DocumentPullDefinition.Repository")
.Include("DocumentPullDefinition.Repository.ConcordanceRepository")
orderby run.PullStarted descending
select run;
IQueryable<DocPullRun> query = sortedPulls.Skip(startRowIndex);
if (maximumRows > 0)
query.Take(maximumRows);
return query.ToList();
}
Take()不改变查询;相反,它返回一个新的表达式,您的代码将忽略该表达式。因此,请将代码更改为:
if (maximumRows > 0)
query = query.Take(maximumRows);
如果只需要最大行数,则不需要if语句。如果它没有达到最大值,那么它将简单地返回它得到的任何东西 你可以说:
return query.Take(maximumRows).ToList();
啊!新手失误!谢谢克雷格!仅当
最大行数
大于0时,此选项才有效。如果maximumRows
为0,则不会显示任何行。但在他的示例中,他希望返回数据库中的所有行。
return query.Take(maximumRows).ToList();