0

我有一张桌子,Measurements它有一Date列。
此列已编入索引(虽然是非唯一索引)

使用 EntityFramework 我想从某个monthand获取所有项目year

问题:就性能而言,哪种替代方案更好?

备选方案 1:

  var results = db.Measurements.Where(m => m.Date.Month == month && m.Date.Year == year);

(生成的 SQL 使用DATEPART函数)

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)))

(......虽然我不确定为什么会有“OR null”的情况)

备选方案 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);

(生成的 SQL 使用运算符>=<=

  WHERE ([Extent1].[Date] >= @p__linq__1) AND ([Extent1].[Date] <= @p__linq__2)
4

0 回答 0