akash
akash

Reputation: 173

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...

Upvotes: 0

Views: 124

Answers (3)

Felix Pamittan
Felix Pamittan

Reputation: 31879

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;

Upvotes: 1

Friyank
Friyank

Reputation: 479

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

Upvotes: 1

VahidN
VahidN

Reputation: 19136

Convert Convert.ToDateTime to a variable and then use it in the query.

Upvotes: 1

Related Questions