SQL慢了Linq慢

时间:2017-09-26 11:19:09

标签: c# sql-server linq tsql

当我尝试下一个linq查询时,它很慢(1.5秒):

var rslt = (from t in context.Set<SUB_Transactions>()
            where
            t.UpdateDate > query.LastUpdate &&
            t.TransactionID > query.Index
            select new
            {
                TransactionID = t.TransactionID
            }).OrderBy(t => t.TransactionID).Take(query.Amount).ToList();

转换为SQL时,此查询超快(40毫秒):

SELECT TOP (300) 
    [Project1].[TransactionID] AS [TransactionID]
    FROM ( SELECT 
        [Extent1].[TransactionID] AS [TransactionID]
        FROM [dbo].[SUB_Transactions] AS [Extent1]
        WHERE ([Extent1].[UpdateDate] > @p__linq__0) AND ([Extent1].[TransactionID] > @p__linq__1)
    )  AS [Project1]
    ORDER BY [Project1].[TransactionID] ASC

这里发生了什么?

删除第一个查询中的Take也会得到快速结果(假设没有新事务的速度很快)

TransactionIDUpdateDate上有一个综合索引。

1 个答案:

答案 0 :(得分:3)

就你的例子而言,这可以使你的查询更快但没有一些样本数据,我们无法从我们的结尾进行测试:

var rslt = (from t in context.Set<SUB_Transactions>()
            where t.TransactionID > query.Index // invert order of filter
               && t.UpdateDate > query.LastUpdate 
            order by t.TransactionID // you can orderby here
            select t.TransactionID) // remove anonymous object
           .Take(query.Amount)
           .AsNoTracking() // you won't be changing IDs so no need to track them
           .ToList();

如果您使用DbSet<SUB_Transactions>而非调用Set<SUB_Transactions>()需要找到DbSet

中的DbContext,您可能也会获得一些效果