C#ADO.NET:空和DBNull的 - 有没有更有效的语法? [英] C# ADO.NET: nulls and DbNull -- is there more efficient syntax?

查看:342
本文介绍了C#ADO.NET:空和DBNull的 - 有没有更有效的语法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个日期时间?我试图用 DbParameter 插入到一个字段。我创建的参数,像这样:

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

然后我想把日期时间? dataPrm.Value ,而占<值code>空秒。

我想一开始我会很聪明的:

  datePrm.Value = nullableDate?的DBNull.Value;
 

但失败,出现错误

  

运营商'?不能应用于类型的操作数的System.DateTime?和System.DBNull

所以我想这只有当第二个参数是第一个参数的不可为空的版本。于是我去了:

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

但是,这并不管用:

  

有条件的前pression类型无法确定,因为没有'System.DateTime的'和'System.DBNull

之间的隐式转换

但我不希望这些类型之间的转换!

到目前为止,我唯一能得到的工作是:

 如果(nullableDate.HasValue)
  datePrm.Value = nullableDate.Value;
其他
  datePrm.Value =的DBNull.Value;
 

这真的是唯一的出路,我可以写这篇文章?有没有一种方法使用三元运营商合作,以获得一个班轮?

更新:我真的不明白,为什么?版本无法正常工作。 MSDN说:

  

的?操作符返回左边的操作数,如果它不为空,否则将返回正确的操作。

这正是我想要的!

UPDATE2:那么这是一种明显的中底:

  datePrm.Value = nullableDate? (对象)的DBNull.Value;
 

解决方案

啊哈!我发现了一个更有效的解决方案比@ Trebz的!

  datePrm.Value = nullableDate? (对象)的DBNull.Value;
 

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:空和DBNull的 - 有没有更有效的语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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