Nullable DateTime and the Database

末鹿安然 提交于 2019-12-08 15:31:38

问题


I've got a nullable datetime object in C#.

DateTime? StartDate = new DateTime();

I then check a user submitted value to determine if a date is applicable to this record:

if (Complete == "N/A")
{
    StartDate = null;
}

Now I come to my query which may or may not be inserting a null datetime:

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

As you'd probably expect if the start date is null then I get an error that the type is not correct. What's the best way to proceed from here?

I have considered checking startdate is null but am not sure how to do that when the type is nullable.


回答1:


This will pass a database NULL value as the parameter if StartDate is null:

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



回答2:


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;
}


来源:https://stackoverflow.com/questions/9099157/nullable-datetime-and-the-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!