Use Linq to SQL to search only time portions of a date in SQL 2008
I want to be able to search on a DateTime field not only by a date range, but also by a time range. For example, "Get me all records in the month of May created between 1pm and 3pm". The SQL I'm looking to generated is:
WHERE CreatedOn BETWEEN '05/01/2010' AND '06/01/2010' AND CONVERT(time(4), CreatedOn) BETWEEN '01:00 PM' AND '03:00 PM'
I can't seem to figure out how to get a lambda expression to get me there. Anybody got any clue? I've got System.Linq.Dynamic in my project. Similar to the way you can pass a string as an OrderBy clause, I thought I might be able to do the same with the Where method as follows::
results = results.Where("CONVERT(time(4), OccurredOn) BETWEEN '{0}' AND '{1}'", Criteria.OffenseTimeStart, Criteria.OffenseTimeEnd);
But that throws an exception in System.Linq.Dynamic. Anybody got any pointers?
THANKS FOR THE HELP! Here is my working code excerpt. I exposed my time criteria properties as TimeSpans:
if (开发者_StackOverflow社区Criteria.OffenseDateStart.HasValue)
results = results.Where(o => o.OccurredOn >= Criteria.OffenseDateStart);
if (Criteria.OffenseDateEnd.HasValue)
results = results.Where(o => o.OccurredOn <= Criteria.OffenseDateEnd);
if (Criteria.OffenseTimeStart.HasValue)
results = results.Where(o => o.OccurredOn.TimeOfDay >= Criteria.OffenseTimeStart);
if (Criteria.OffenseTimeEnd.HasValue)
results = results.Where(o => o.OccurredOn.TimeOfDay <= Criteria.OffenseTimeEnd);
I don't think you can do a 'Between', but you can write a linq query like:
where (x.CreatedOn.Date >= myDate.Date && x.CreatedOn.Date <= myDate2.Date)
&& (x.CreatedOn.TimeOfDay >= TimeSpan.Parse("13:00") && x.CreatedOn.TimeOfDay <= TimeSpan.Parse("15:00"))
Something like this?
results = results.Where(x => x.OccurredOn.Date >= Criteria.OffenseDateStart.Date
&& x.OccurredOn.Date <= Criteria.OffenseDateEnd.Date
&& x.OccurredOn.TimeOfDay >= Criteria.OffenseTimeStart.TimeOfDay
&& x.OccurredOn.TimeOfDay <= Criteria.OffenseTimeEnd.TimeOfDay);
(Assuming that OccurredOn
, OffenseDateStart
, OffenseDateEnd
, OffenseTimeStart
and OffenseTimeEnd
are all typed as DateTime
.)
精彩评论