[英]Does raw SQL run faster than the equivalent LINQ methods?
I have this method that returns the Count of rows with the given search criteria: 我有这种方法,返回具有给定搜索条件的行数:
public int HistoryCount(Guid id, string tableName)
{
int sqlCount = context.Database.SqlQuery<int>("SELECT COUNT(*) FROM
COMMON.TbHistoryLog WHERE ObjectId = '" + id + "'
AND TableName = '" + tableName + "'").First();
FuncHistory = x => x.ObjectId == id && x.TableName == tableName;
return AuditHelper.HistoryCount(context.TbHistoryLog, FuncHistory);
}
and this is AuditHelper.HistoryCount
method: 这是
AuditHelper.HistoryCount
方法:
public static int HistoryCount<TSet>(DbSet<TSet> set, Func<TSet, bool> predict) where TSet : class
{
var auditCount = set.Count(predict);
return auditCount;
}
I was running into long querying time when executing AuditHelper.HistoryCount method, and then I tried to run the same query (I guess) using raw SQL, which returned the result immediately. 执行AuditHelper.HistoryCount方法时,查询时间很长,然后尝试使用原始SQL运行相同的查询(我想),该查询立即返回结果。
Is there something wrong with my implementation or raw SQL is faster than the equivalent LINQ methods? 我的实现有问题吗,还是原始SQL比同等的LINQ方法快?
Because you are using Count(Func<>)
in your helper function, you are calling Enumerable.Count()
which means you are pulling all records from the database and then processing the predicate and count locally. 因为您在助手函数中使用
Count(Func<>)
,所以您正在调用Enumerable.Count()
,这意味着您要从数据库中提取所有记录,然后在本地处理谓词和计数。 You need to use Expression<Func<>>
to use Queryable.Count()
that will be processed by the SQL server: 您需要使用
Expression<Func<>>
来使用将由SQL Server处理的Queryable.Count()
:
public static int HistoryCount<TSet>(DbSet<TSet> set, Expression<Func<TSet, bool>> predict) where TSet : class {
var auditCount = set.Count(predict);
return auditCount;
}
Then code it like so: 然后像这样编码:
return AuditHelper.HistoryCount(context.TbHistoryLog, x => x.ObjectId == id && x.TableName == tableName);
Or declare FuncHistory
to be Expression
: 或将
FuncHistory
声明为Expression
:
Expression<Func<TBHistoryLog, bool>> FuncHistory = x => x.ObjectId == id && x.TableName == tableName;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.