I have a table, Measurements
, which has a Date
column.
This column is indexed (is a non unique index though)
Using EntityFramework I want to get all items from a certain month
and year
.
Question: What alternative is better in terms of performance?
Alternative 1:
var results = db.Measurements.Where(m => m.Date.Month == month && m.Date.Year == year);
(The resultant SQL uses the DATEPART
function)
WHERE (((DATEPART (month, [Extent1].[Date])) = @p__linq__1) OR ((DATEPART (month, [Extent1].[Date]) IS NULL) AND (@p__linq__1 IS NULL))) AND (((DATEPART (year, [Extent1].[Date])) = @p__linq__2) OR ((DATEPART (year, [Extent1].[Date]) IS NULL) AND (@p__linq__2 IS NULL)))
(...though I'm not sure why there is a "OR null" case)
Alternative 2:
DateTime firstDateOfMonth = new DateTime(year, month, 1);
DateTime lastDateOfMonth = new DateTime(year, month, DateTime.DaysInMonth(year, month));
var results = db.Measurements.Where(m => m.Date >= firstDateOfMonth && m.Date <= lastDateOfMonth);
(The resultant SQL uses operators >=
and <=
)
WHERE ([Extent1].[Date] >= @p__linq__1) AND ([Extent1].[Date] <= @p__linq__2)