c# - 可空日期时间和数据库

标签 c# visual-web-developer

我在 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/

相关文章:

c# - "You cannot save a class that does not contain a property that represents the item ID"当 GlassCast(ing) 分支模板项时,为什么?

javascript - 删除 Visual Studio Web Developer Express 2012 中的注释代码

javascript - 使导航栏的背景在滚动时改变

c# - JObject 结构 - 如何迭代?

c# - 字符串字母验证

asp.net - 为什么当我编辑 css 页面时文本没有改变颜色?

CSS:Courier 字体在 Windows 和 iOS 上呈现不一致

c# - Visual Web 开发人员控制台应用程序,如何

c# - 当需要设计模块化架构时,对象转换是现实的必然吗?

c# - 如何使用ajax将部分 View 返回为html