C# 可为空的DateTime和数据库

C# 可为空的DateTime和数据库,c#,visual-web-developer,C#,Visual Web Developer,我在C#中有一个可为空的datetime对象 然后,我检查用户提交的值,以确定日期是否适用于此记录: if (Complete == "N/A") { StartDate = null; } 现在我来谈谈我的查询,它可能插入空datetime,也可能不插入空datetime: using (SqlCommand command = new SqlCommand(updateSql, db)) { command.Parameters.Add("@Date_Started", S

我在C#中有一个可为空的datetime对象

然后,我检查用户提交的值,以确定日期是否适用于此记录:

if (Complete == "N/A")
{
    StartDate = null;
}
现在我来谈谈我的查询,它可能插入空datetime,也可能不插入空datetime:

using (SqlCommand command = new SqlCommand(updateSql, db))
{
    command.Parameters.Add("@Date_Started", SqlDbType.DateTime).Value = StartDate;
}
正如您可能期望的那样,如果开始日期为null,那么我会得到一个类型不正确的错误。从这里开始最好的方法是什么


我考虑过检查startdate是否为null,但不确定在类型可为null时如何进行检查。

如果startdate为null,这将传递一个数据库null值作为参数:

using (SqlCommand command = new SqlCommand(updateSql, db))
{
    command.Parameters.Add("@Date_Started", SqlDbType.DateTime).Value = (object)StartDate ?? DBNull.Value;
}

这就是我所尝试的,但我不知道这种速记语法!:)此操作也有错误:运算符“??”不能应用于system.datetime类型的操作数?和system.dbnull。@deed02392使用简单的对象转换作为旁白进行修复,您可以通过两种方式轻松检查可空类型是否为null。1)
!StartDate.HasValue
,或2)只需
StartDate==null
using (SqlCommand command = new SqlCommand(updateSql, db))
{
    command.Parameters.Add("@Date_Started", SqlDbType.DateTime).Value = (object)StartDate ?? DBNull.Value;
}
using (SqlCommand command = new SqlCommand(updateSql, db))
{
    if (StartDate.HasValue())
        command.Parameters.Add("@Date_Started", SqlDbType.DateTime).Value
            = StartDate;
    else
        command.Parameters.Add("@Date_Started", SqlDbType.DateTime).Value 
            = DBNull.Value;
}