我想从 x.CreatedDate 中获取年份,该怎么做?
I want to fetch Year from x.CreatedDate how to do that?
_dbEntities.Salaries.Where(x => x.EmployeeID == EmployeeID && x.MonthID == MonthID && x.CreatedDate == Year).SingleOrDefault();
我想从 x.CreatedDate 中获取年份,该怎么做?
您可以只检查 DateTime
对象的 Year
属性。它必须有效:
_dbEntities.Salaries.Where(x => x.EmployeeID == EmployeeID &&
x.MonthID == MonthID &&
x.CreatedDate.Year == Year)
.SingleOrDefault();
如果此列可以为空,则必须将其更改为:x.CreatedDate.Value.Year == Year
我刚刚在 LinqToEntity
中针对 MS Sql 服务器数据库进行了检查,它工作正常。
P.S: 我想他们已经删除了 EntityFunctions.Year()
并用这个替换了它。
在比较之前转换数据库字段值可能会影响性能,因为它会禁用该字段上的任何索引(表达式不是 sargeable)。因此,虽然 Farhad 的解决方案可能没问题(因为您还过滤了其他高度选择性的字段),并且值得接受,但可能更好
var lowerBound = new DateTime(year, 1, 1);
var upperBound = new DateTime(year + 1, 1, 1);
_dbEntities.Salaries
.Where(x => x.EmployeeID == EmployeeID
&& x.MonthID == MonthID
&& x.CreatedDate >= lowerBound)
&& x.CreatedDate < upperBound)
.SingleOrDefault();
_dbEntities.Salaries.Where(x => x.EmployeeID == EmployeeID && x.MonthID == MonthID && x.CreatedDate == Year).SingleOrDefault();
我想从 x.CreatedDate 中获取年份,该怎么做?
您可以只检查 DateTime
对象的 Year
属性。它必须有效:
_dbEntities.Salaries.Where(x => x.EmployeeID == EmployeeID &&
x.MonthID == MonthID &&
x.CreatedDate.Year == Year)
.SingleOrDefault();
如果此列可以为空,则必须将其更改为:x.CreatedDate.Value.Year == Year
我刚刚在 LinqToEntity
中针对 MS Sql 服务器数据库进行了检查,它工作正常。
P.S: 我想他们已经删除了 EntityFunctions.Year()
并用这个替换了它。
在比较之前转换数据库字段值可能会影响性能,因为它会禁用该字段上的任何索引(表达式不是 sargeable)。因此,虽然 Farhad 的解决方案可能没问题(因为您还过滤了其他高度选择性的字段),并且值得接受,但可能更好
var lowerBound = new DateTime(year, 1, 1);
var upperBound = new DateTime(year + 1, 1, 1);
_dbEntities.Salaries
.Where(x => x.EmployeeID == EmployeeID
&& x.MonthID == MonthID
&& x.CreatedDate >= lowerBound)
&& x.CreatedDate < upperBound)
.SingleOrDefault();