How to Convert a Nullable DateTime variable's null value to DbNull.Value

允我心安 提交于 2019-12-23 17:12:26

问题


I have a nullable DateTime Variable. And I want to write it to SQL DB. When i try to insert:

If the variable has value there is no problem.

But if it hasn't a value, insertion interrupting with an error.

I want to ask: How can we insert nullable DateTime to Sql via DbCommand Parameter?

(P.S. : Sql column is nullable too.)

DateTime? myDate = null;
DbCommand dbCommand = new DbCommand();
dbCommand.Parameters.Add("NullableSqlDateField", DbType.DateTime, myDate);

回答1:


Try the null coalescing operator:

dbCommand.Parameters.Add("NullableSqlDateField", DbType.DateTime, (object) myDate ?? DbNull.Value);



回答2:


try this

if(myDate.HasValue)
  dbCommand.Parameters.Add("NullableSqlDateField", DbType.DateTime, myDate.Value);
else
  dbCommand.Parameters.Add("NullableSqlDateField", DbType.DateTime, DbNull.Value);


来源:https://stackoverflow.com/questions/8669107/how-to-convert-a-nullable-datetime-variables-null-value-to-dbnull-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!