如何将Nullable DateTime变量的null值转换为DbNull.Value

Dor*_*Gen 3 c# sql-server datetime nullable dbcommand

我有一个可以为空的DateTime变量.我想把它写到SQL DB.当我尝试插入时:

如果变量有值,则没有问题.

但如果它没有值,则插入中断错误.

我想问:我们如何通过DbCommand参数将可空的DateTime插入Sql?

(PS:Sql列也可以为空.)

DateTime? myDate = null;
DbCommand dbCommand = new DbCommand();
dbCommand.Parameters.Add("NullableSqlDateField", DbType.DateTime, myDate);
Run Code Online (Sandbox Code Playgroud)

mat*_*att 12

尝试null合并运算符:

dbCommand.Parameters.Add("NullableSqlDateField", DbType.DateTime, (object) myDate ?? DbNull.Value);
Run Code Online (Sandbox Code Playgroud)

  • 我有点惊讶这不是由db提供程序处理的. (3认同)