Search code examples
sqllinqsql-to-linq-conversion

why my linq query is not giving me expected results


I have this sql query

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 });

it is working fine for sql query,but when I used linq query for getting same results it gives error
and thanks in advance...


Solution

  • Try using new DateTime() for your date constants. Additionally, you can use SqlMethods.DateDiffMinute to get the minute difference and .Sum() to get the 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;