简体   繁体   中英

LINQ to Entities - Comparing Dates

Is there a better (nicer/more efficient) way to do this?

return View(db.Things
    .Where(t => t.DateTimeObj.Month == DateTime.Today.Month 
        && t.DateTimeObj.Day == DateTime.Today.Day)
    .OrderByDescending(e => e.DateTimeObj)
    .Take(num)
);

The following do not work (no Date object in LINQ to Entites).

Todays records:

return View(db.Things
    .Where(t => t.DateTimeObj.Date == DateTime.Today)
    .OrderByDescending(e => e.DateTimeObj)
    .Take(num)
);

Last 24 hours records:

return View(db.Things
    .Where(t => t.DateTimeObj > DateTime.Today.AddHours(-24))
    .OrderByDescending(e => e.DateTimeObj)
    .Take(num)
);

Edit:

This seems to do the trick:

return View(db.Things
    .Where(t => t.DateTimeObj > SqlFunctions.DateAdd("dd", -1, DateTime.Now))
    .OrderByDescending(e => e.DateTimeObj)
    .Take(num)
);

Possible gotchas as pointed out by Chris Sainty:

  1. SQL Server only (probably?)
  2. Date computations are held off to be performed by SQL Server, as oposed to supplying a pre computed date in the linq2sql translation.

Take a look at the SqlFunctions class on msdn which provides access to the sql datediff etc functions.

Note they can not be used to run the code in C# they are just placeholders that the query parser understands and can convert to T-SQL. Obviously this is SQL Server only unless other providers have wrapped these functions.

Simply declare your 'compare to' dates before hand

var today = DateTime.Today;
return View(db.Things
    .Where(t => t.DateTimeObj.Date == today)
    .OrderByDescending(e => e.DateTimeObj)
    .Take(num)
);

//Last 24 hours records:
var yesterday = DateTime.Now.AddDays(-1);
return View(db.Things
    .Where(t => t.DateTimeObj > yesterday)
    .OrderByDescending(e => e.DateTimeObj)
    .Take(num)
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM