无法将 DBNull.Value 转换为类型“System.DateTime".请使用可空类型 [英] Cannot cast DBNull.Value to type 'System.DateTime'. Please use a nullable type

查看:41
本文介绍了无法将 DBNull.Value 转换为类型“System.DateTime".请使用可空类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码

var finalResults = (from r in results.AsEnumerable()
                    where r.Field<DateTime>("PrintTime") is DBNull

其中 PrintTime 是我的 Sql Server 2008 r2 数据库中的一列,它的类型是 datetime 并且它是 nullable

where PrintTime is a column in my Sql Server 2008 r2 database, its type is datetime and it is nullable

我遇到了这个异常:

无法将 DBNull.Value 转换为类型System.DateTime".请使用一个可空类型.

Cannot cast DBNull.Value to type 'System.DateTime'. Please use a nullable type.

你能帮忙吗?

推荐答案

DataRow.Field 支持可空类型,所以使用 DateTime? 而不是 DateTime:

var finalResults = from r in results.AsEnumerable()
                   let printTime = r.Field<DateTime?>("PrintTime")
                   where !printTime.HasValue
                   select r;

这篇关于无法将 DBNull.Value 转换为类型“System.DateTime".请使用可空类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆