dee*_*392 11 c# visual-web-developer
我在C#中有一个可以为空的datetime对象.
DateTime? StartDate = new DateTime();
Run Code Online (Sandbox Code Playgroud)
然后,我检查用户提交的值,以确定日期是否适用于此记录:
if (Complete == "N/A")
{
StartDate = null;
}
Run Code Online (Sandbox Code Playgroud)
现在我来查询可能会或可能不会插入空日期时间:
using (SqlCommand command = new SqlCommand(updateSql, db))
{
command.Parameters.Add("@Date_Started", SqlDbType.DateTime).Value = StartDate;
}
Run Code Online (Sandbox Code Playgroud)
正如您可能期望的那样,如果开始日期为null,那么我会收到类型不正确的错误.从这里开始的最佳方式是什么?
我考虑过检查startdate是null但是当类型可以为空时我不知道该怎么做.
Roy*_*ode 18
如果StartDate为null,这将传递数据库NULL值作为参数:
using (SqlCommand command = new SqlCommand(updateSql, db))
{
command.Parameters.Add("@Date_Started", SqlDbType.DateTime).Value = (object)StartDate ?? DBNull.Value;
}
Run Code Online (Sandbox Code Playgroud)