转换为价值类型' System.Datetime'失败,因为具体化值为null

时间:2016-01-12 14:27:40

标签: c# .net linq datetime null

我知道此错误非常常见,但我无法使用一种数据和DateTime类型处理错误。

这是我的LINQ:

var lastDate = (
    from t in context.table select t.CreatedOn
).Max();

我需要的是获取最后一行的DateTimeCreatedOn)字段。
事情就是崩溃,因为表是空的,我无法在catch异常之前处理null。使用数据可以。

更新:
预期的结果是" null"如果日期时间不能得到。

通过Pikoh评论,我可以做到,但现在我有一个带有条件的linq的相同错误(其中)

                        lastDateWithCriteria= (
          from t in context.table
where criteria == "value"
          select t.CreatedOn).Max();
                    }

2 个答案:

答案 0 :(得分:5)

你可以做的一件事是......

var lastDate = (
    from t in context.table select (DateTime?)t.CreatedOn
).Max();

通过此演员,您可以告诉您的代码,CreatedOn字段现在可以为空。

如果您愿意,您甚至可以在值为空时传递默认值...

var lastDate = (
        from t in context.table select (DateTime?)t.CreatedOn
    ).Max() ?? DateTime.Now;

我希望有所帮助。

答案 1 :(得分:1)

采取不同的方法:

var lastRow = (
    from t in context.table 
    orderby t.CreatedOn descending
    select new { t.CreatedOn }
).FirstOrDefault();

if (lastRow != null) 
    Console.WriteLine(lastRow.CreatedOn)

它创建一个仅包含日期的匿名对象。因此,它将与空结果一起使用。

相关问题