博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
关于DBNull.Value
阅读量:5739 次
发布时间:2019-06-18

本文共 1563 字,大约阅读时间需要 5 分钟。

I've got a DateTime? that I'm trying to insert into a field using a DbParameter. I'm creating the parameter like so:

DbParameter datePrm = updateStmt.CreateParameter(); datePrm.ParameterName = "@change_date";

And then I want to put the value of the DateTime? into the dataPrm.Value while accounting for nulls.

I thought initially I'd be clever:

datePrm.Value = nullableDate ?? DBNull.Value;

but that fails with the error

Operator '??' cannot be applied to operands of type 'System.DateTime?' and 'System.DBNull'

So I guess that only works if the second argument is a non-nullable version of the first argument. So then I went for:

datePrm.Value = nullableDate.HasValue ? nullableDate.Value : DBNull.Value;

but that doesn't work either:

Type of conditional expression cannot be determined because there is no implicit conversion between 'System.DateTime' and 'System.DBNull'

But I don't want to convert between those types!

So far the only thing I can get to work is:

if (nullableDate.HasValue)   datePrm.Value = nullableDate.Value; else   datePrm.Value = DBNull.Value;

Is that really the only way I can write this? Is there a way to get a one-liner using the ternary operator to work?

Update: I don't really get why the ?? version doesn't work. MSDN says:

The ?? operator returns the left-hand operand if it is not null, or else it returns the right operand.

That's exactly what I want!

Update2: Well it was kind of obvious in the end:

datePrm.Value = nullableDate ?? (object)DBNull.Value;
本文转自 h2appy  51CTO博客,原文链接:http://blog.51cto.com/h2appy/415825,如需转载请自行联系原作者
你可能感兴趣的文章
原生CSS设置网站主题色—CSS变量赋值
查看>>
webpack 4.0 中 clean-webpack-plugin 的使用
查看>>
WPF
查看>>
中文词频统计
查看>>
POJ 2236 Wireless Network (并查集)
查看>>
python分类
查看>>
GitBlit (1)-- 在linux 安装 GitBlit 并运行
查看>>
Windows与Linux之间的文件自动同步
查看>>
程序是如何执行的(一)a=a+1
查看>>
go : 结构
查看>>
18 已知下面的字符串是通过RANDOM随机数变量md5sum|cut-c 1-8截取后的结果
查看>>
BZOJ - 3578: GTY的人类基因组计划2
查看>>
理解WebKit和Chromium(电子书)
查看>>
爱——无题
查看>>
分布式服务框架原来与实践 读书笔记一
查看>>
【http】post和get请求的区别
查看>>
TFS强制撤销某个工作区的文件签出记录
查看>>
EL表达式无法显示Model中的数据
查看>>
ps6-工具的基础使用
查看>>
灵活运用 SQL SERVER FOR XML PATH
查看>>