C# ADO.NET:null 和 DbNull——有更高效的语法吗?

C# ADO.NET: nulls and DbNull -- is there more efficient syntax?(C# ADO.NET:null 和 DbNull——有更高效的语法吗?)
本文介绍了C# ADO.NET:null 和 DbNull——有更高效的语法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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;

解决方案

Ah ha! I found an even more efficient solution than @Trebz's!

datePrm.Value = nullableDate ?? (object)DBNull.Value;

这篇关于C# ADO.NET:null 和 DbNull——有更高效的语法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)