Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq: Difference between 2 DateTimes in TimeSpan

I'm trying to do this:

Tickets.Where(t => (t.Date - myTicket.Date) < TimeSpan.FromSeconds(120));

I'm getting the "DbArithmeticExpression arguments must have a numeric common type" error. How can I do this, considering that I need the difference in a TimeSpan?

Thanks in advance.

like image 617
Leila Avatar asked Apr 18 '12 17:04

Leila


3 Answers

You would want to use SqlFunctions.DateDiff

Tickets.Where(t => 
      SqlFunctions.DateDiff("second", t.Date, myTicket.Date) < 120));
like image 141
Magnus Avatar answered Oct 05 '22 02:10

Magnus


You can also use this;

var result = db.Tickets.Where(t => 
       SqlMethods.DateDiffSecond(myTicket.Date ,  t.Date) < 120);
like image 24
Çağatay Ay Avatar answered Oct 05 '22 02:10

Çağatay Ay


Arithmetic with DateTime is not supported in Entity Framework. You have to use one of the SqlFunctions. So, for your statement, something like:

Tickets.Where(t => 
      SqlFunctions.DateDiff("second", t.Date, myTicket.Date) < 120));
like image 36
Cinchoo Avatar answered Oct 05 '22 01:10

Cinchoo