3

I am trying to delete all items which are older than 3 hours in a table, but get the following error...

DbArithmeticExpression arguments must have a numeric common type.

// Method to clean items in baskets table which are over 3 hours old.
public void CleanBasket()
{
    var expired = (from a in db.Baskets
                   where (DateTime.Now - a.DateCreated).TotalHours > 3  select a);
    foreach (Basket basket in expired) db.DeleteObject(expired);
    db.SaveChanges();
}

I have never seen this error before, can anybody help me to debug please?

FYI, I have also tried... var expired = (from a in db.Baskets where (DateTime.Now.Subtract(a.DateCreated).Hours > 3) select a);

but I get the error message "LINQ to Entities does not recognize the method 'System.TimeSpan Subtract(System.DateTime)' method, and this method cannot be translated into a store expression."

Gravy
  • 12,264
  • 26
  • 124
  • 193

2 Answers2

2

EF doesn't support DateTime - DateTime.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • I've tried changing 3 to 3d and also to 3.0 and both give me the same error message – Gravy Apr 23 '12 at 23:05
  • I get the same error when trying where (DateTime.Now - a.DateCreated).TotalHours > 3d select a); – Gravy Apr 23 '12 at 23:10
0

You need to use System.Data.Entity.DbFunctions.DiffHours as per this answer:

https://stackoverflow.com/a/9860858/345659

var expired = (from a in db.Baskets
               where DbFunctions.DiffHours(DateTime.Now, a.DateCreated) > 3
               select a);
Community
  • 1
  • 1
JumpingJezza
  • 5,498
  • 11
  • 67
  • 106