0

I have a query which returns true or false depending on two conditions. One of the conditions is check whether the time (today's time) from the DB is less than or equal to 5 minutes (i.e 300 seconds). I tried defining a variable of DateTime format as follows

System.DateTime customDate= new System.DateTime(0000, 00, 00, 0, 00, 300);

here is the query

bool result = (from a in this.db.Samples
               where a.Ping == "Online" 
               && 
              (EntityFunctions.TruncateTime(a.date) - DateTime.Now) <= customDate                 
               select a).Any();

but I have the following error

Operator '<=' cannot be applied to operands of type 'System.TimeSpan?' and System.DateTime'

kindly help.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Indhi
  • 1,684
  • 5
  • 27
  • 48

1 Answers1

1

Subtracting one DateTime from another results in a TimeSpan. EntityFramework doesn't support DateTime/TimeSpan arithmetic so you'll have to use the DiffMinutes entity function. (Full list of entity functions).

Try:

bool result = (from a in this.db.Samples
               where a.Ping == "Online" 
               && 
               EntityFunctions.DiffMinutes(EntityFunctions.TruncateTime(a.date), DateTime.Now) <= 5
               select a).Any();
Neil Mountford
  • 1,951
  • 3
  • 21
  • 31
  • Thanks for your update, but I have the following error - "DbArithmeticExpression arguments must have a numeric common type". – Indhi Jul 05 '13 at 11:26
  • I've edited the answer to reflect the need for the Entity Functions for any kind of DateTime/TimeSpan arithmetic. You can use the DiffMinutes Entity Function to get the difference in minutes between a start and end date. – Neil Mountford Jul 05 '13 at 11:51
  • Yes, the 5 is minutes. The Diff functions all return an Int32 so you could use DiffSeconds if you wanted to get the difference in seconds. Take a look at http://msdn.microsoft.com/en-us/library/bb738563.aspx for all of the Diff functions. – Neil Mountford Jul 05 '13 at 13:28