【问题标题】:Nullable DateTime and the Database可空日期时间和数据库
【发布时间】:2012-02-01 16:10:03
【问题描述】:

我在 C# 中有一个可为空的日期时间对象。

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 是否为空,但不知道当类型可以为空时该怎么做。

【问题讨论】:

  • 顺便说一句,您可以通过两种方式轻松检查可空类型是否为空。 1) !StartDate.HasValue, 或 2) 简单的 StartDate == null

标签: c# visual-web-developer


【解决方案1】:

如果 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 通过简单的对象转换来修复
【解决方案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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    相关资源
    最近更新 更多