I have tried the following (obviously without the //), but I can't get any to work, can anybody help please?
public void CleanBasket()
{
//double validHours = 3;
// var expired = (from a in db.Baskets where (DateTime.Now - a.DateCreated).TotalHours > validHours select a);
//var expired = (from a in db.Baskets where (DateTime.Now.Subtract(a.DateCreated).Hours > 3) select a);
//var expired = (from a in db.Baskets where(a => a.DateCreated > DateTime.Now.AddHours(-1));
//foreach (Basket basket in expired) db.DeleteObject(expired);
db.SaveChanges();
}
In this case surely you can simply do your date time calculation before you invoke LINQ:
double validHours = 3;
var latest = DateTime.UtcNow.AddHours(-validHours);
var expired = (from a in db.Baskets where a.DateCreated < latest select a);
For any more complex DateTime operations that you need to do in the database and cannot do this way you can use SqlFunctions.
BTW you should store your times in Utc not local time. Calculations using DateTime.Now
will be wrong during daylight savings time changes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With