强制转换为值类型';System.Datetime';失败,因为具体化的值为null
本文关键字:因为 具体化 null 失败 Datetime 类型 转换 System | 更新日期: 2023-09-27 18:30:09
我知道这个错误很常见,但我不能用一个数据和DateTime
类型来处理它。
这是我的LINQ:
var lastDate = (
from t in context.table select t.CreatedOn
).Max();
我需要的是得到最后一个DateTime
(CreatedOn
)字段,得到行的最大值
问题是崩溃,因为表是空的,我无法在catch异常之前处理null。有了数据,它就起作用了。
更新:
如果无法获取日期时间,则预期结果为"null"。
有了Pikoh的评论,我可以做到,但现在我遇到了同样的错误,linq有一个条件(其中)
lastDateWithCriteria= (
from t in context.table
where criteria == "value"
select t.CreatedOn).Max();
}
你可以做的一件事是…
var lastDate = (
from t in context.table select (DateTime?)t.CreatedOn
).Max();
通过这个强制转换,您可以告诉代码字段CreatedOn现在可以为null。
如果你愿意,你甚至可以传递一个默认值,以防值为null。。。
var lastDate = (
from t in context.table select (DateTime?)t.CreatedOn
).Max() ?? DateTime.Now;
我希望这能有所帮助。
采用不同的方法:
var lastRow = (
from t in context.table
orderby t.CreatedOn descending
select new { t.CreatedOn }
).FirstOrDefault();
if (lastRow != null)
Console.WriteLine(lastRow.CreatedOn)
它创建一个只包含日期的匿名对象。因此,它将以空的结果工作。