您可以像这样检索可为空的datetimeoffset的月份:
DateTimeOffset? dt;
dt?.Value.Month;
但是,我真的很怀疑EF是否可以翻译此内容:
x => x.ApplyDate?.Month == f
转换为SQL表达式。我认为它将回退到内存过滤。
除此之外,即使EF能够将其转换为SQL表达式,它也不是最佳选择,因为将不使用可能在该列上定义的索引。
因此,我建议将您的LINQ表达式重写为如下形式:
x :> x.ApplyDate != null && x.ApplyDate >= new DateTimeOffset(someDate.Year,someDate.Month,1) && x.ApplyDate <= new DateTimeOffset(someDate.Year,daysInMonth)
(鉴于您要检索特定年份中特定月份的数据。如果您想要检索特定月份中的记录,而与年份无关,我看不到其他选择)
,
DateTimeOffset?
是Nullable
类型,因此没有ToString(string format)
那样的DateTimeOffset
超载。
可以从DateTimeOffset?
获取月份值
-
x.ApplyDate.Value.ToString("MM"
)
-
x.ApplyDate.Value.Month
请考虑在获取其“月份”属性之前,请检查ApplyDate.Value
是否为空
,
您上面的代码显示的是DateTime,而不是DateTimeOffSet。
DateTimeOffSet是Struct,如果您有一个可空值,则需要先检查该值,然后从值部分中获取月份
DateTimeOffSet myNullableDateTime = someValue...//
选项1:
// notice I added value below
myNullableDateTime.HasValue? "?Month="+myNullableDateTime.EscapeDataString(myNullableDateTime.Value.ToString()):"")
选项2:
if(myNullableDateTime.HasValue)
{
var Month = myNullableDateTime.Month
TimeSpan difference = DateTimeOffset.Now.Subtract(myNullableDateTime.Value);
// convert the difference to what you need and get Month
}
我还没有编译它,但是它应该可以为您解答或相当接近。
本文链接:https://www.f2er.com/2624185.html