为什么我的linq查询没有给我预期的结果

时间:2016-04-15 06:22:54

标签: sql linq sql-to-linq-conversion

我有这个SQL查询

SELECT SUM(DATEDIFF(MINUTE, InTime , OutTime)) /60
FROM Attendance
WHERE InTime BETWEEN '01-01-2016' AND '01-31-2016' 
AND Employee=63 

 var AttendofEmp = (from ab in db.Attendances 
                    where ab.InTime >= Convert.ToDateTime("01-01-2016") && 
                          ab.InTime >= Convert.ToDateTime("01-31-2016")
                         select new { ab.InTime });

它适用于sql查询,但是当我使用linq查询获得相同的结果时,它会给出错误           并提前感谢...

3 个答案:

答案 0 :(得分:1)

尝试使用new DateTime()作为日期常量。此外,您可以使用SqlMethods.DateDiffMinute获取分钟差异,.Sum()获得总和:

var AttendofEmp  =
    (from a in db.Attendances
     where a.InTime >= new DateTime(2016, 1, 4) && a.InTime <= new DateTime(2016, 1, 31)
     select SqlMethods.DateDiffMinute(a.InTime , a.OutTime)
    ).Sum() / 60;

答案 1 :(得分:1)

Convert.ToDateTime转换为变量,然后在查询中使用它。

答案 2 :(得分:1)

var Date1 = Convert.ToDateTime("01-01-2016");
var Date2 = Convert.ToDateTime("01-31-2016")

     var AttendofEmp = (from ab in db.Attendances 
                        where ab.InTime >= Date1  && 
                              ab.InTime >= Date2 
                             select new { ab.InTime });