将使用CAST调用的SQL查询转换为LINQ

时间:2015-04-17 06:46:58

标签: c# linq

如何将此SQL查询转换为Linq?

Declare @Date Date 
select @Date = Max (InsertedDate) from Rates

SELECT * FROM Rates where CAST(InsertedDate AS Date) =CAST(@Date AS Date)  ORDER BY InsertedDate DESC 

1 个答案:

答案 0 :(得分:1)

您的Sql查询似乎找到上次插入日期的所有记录。你的Sql大致相当于:

var lastDate = db.Rates.Max(r => r.InsertedDate).Date;
var allRatesOnTheLastDate = db.Rates.Where(r => r.InsertedDate >= lastDate)
                                    .OrderByDescending(r => r.InsertedDate);

这应该比您的Sql更高效,因为您正在转换InsertedDate列,这将阻止列上任何索引的SARGability

(假设一个名为db的EF或Linq2Sql上下文绑定了一个Rates实体)