如何可空日期时间变量的空值转换为DbNull.Value [英] How to Convert a Nullable DateTime variable's null value to DbNull.Value

查看:433
本文介绍了如何可空日期时间变量的空值转换为DbNull.Value的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可为空的DateTime变量。我想将它写入SQL数据库。当我尝试插入:



如果变量具有值是没有问题的。



但是,如果它没有价值,插入一个错误中断。



我要问: ?我们怎样才能插入可空的DateTime通过的DbCommand参数设置为SQL



(PS:SQL列可以为空了。)

 日期时间?数值指明MyDate = NULL; 
的DbCommand的DbCommand =新的DbCommand();
dbCommand.Parameters.Add(NullableSqlDateField,DbType.DateTime,数值指明MyDate);


解决方案

尝试的null合并运算符

 的DbCommand .Parameters.Add(NullableSqlDateField,DbType.DateTime,(对象)的数值指明MyDate?DbNull.Value); 


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);

解决方案

Try the null coalescing operator:

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

这篇关于如何可空日期时间变量的空值转换为DbNull.Value的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆