我在 C# 中有一个可为 null 的日期时间对象。
DateTime? StartDate = new DateTime();
然后我检查用户提交的值以确定日期是否适用于此记录:
if (Complete == "N/A")
{
StartDate = null;
}
现在我开始查询,它可能插入也可能不插入空日期时间:
using (SqlCommand command = new SqlCommand(updateSql, db))
{
command.Parameters.Add("@Date_Started", SqlDbType.DateTime).Value = StartDate;
}
正如您可能预料的那样,如果开始日期为空,那么我会收到类型不正确的错误消息。从这里开始的最佳方式是什么?
我考虑过检查 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;
}
关于c# - 可空日期时间和数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9099157/