处理DateTime DBNull [英] Handling a DateTime DBNull

查看:160
本文介绍了处理DateTime DBNull的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了很多很多版本的SO,但是没有一个似乎对我的需要很有用。

I have seen many, many versions of this on SO, but none of them seem to quite work for my needs.

我的数据来自一个允许DateTime字段为null的供应商数据库。首先我将数据拉入DataTable。

My data comes from a vendor database that allows null for DateTime fields. First I pull my data into a DataTable.

using (SqlCommand cmd = new SqlCommand(sb.ToString(), conn))
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
    da.Fill(dt);
}

我正在将DataTable转换为列表<>进行处理。 >

I am converting a DataTable to a List<> for processing.

var equipment = from i in dt.AsEnumerable()
    select new Equipment()
    {
        Id = i.Field<string>("ID"),
        BeginDate = i.Field<DateTime>("BeginDate"),
        EndDate = i.Field<DateTime>("EndDate"),
        EstimatedLife = i.Field<double>("EstimatedLife")
    }



So, how do I check for DBNull in this instance? I tried to write a method.

    public DateTime CheckDBNull(object dateTime)
    {
        if (dateTime == DBNull.Value)
            return DateTime.MinValue;
        else
            return (DateTime)dateTime;
    }


推荐答案

一个可能的选项是存储作为一个可空的日期时间与语法 DateTime?

One possible option is store it as a nullable date time with the syntax DateTime?

这是一个链接到MSDN 关于使用可空类型

Here is a link to the MSDN about using nullable types

这篇关于处理DateTime DBNull的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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