null分配到的SqlParameter [英] Assign null to a SqlParameter

查看:281
本文介绍了null分配到的SqlParameter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下code给出了一个错误 - 从没有DBNull的隐式转换为int

 的SqlParameter [] =参数新的SqlParameter [1];
的SqlParameter planIndexParameter =新的SqlParameter(@ AgeIndex,SqlDbType.Int);
planIndexParameter.Value =(AgeItem.AgeIndex == NULL)? DBNull.Value:AgeItem.AgeIndex;
参数[0] = planIndexParameter;


解决方案

的问题是,操作员无法确定返回类型,因为你要么返回一个 INT 值或为DBNull类型值,这是不兼容的。

您当然可以投AgeIndex的实例是类型对象这将满足要求。

您可以使用 ?? 空合并运算符如下:

 的SqlParameter [] =参数新的SqlParameter [1];
的SqlParameter planIndexParameter =新的SqlParameter(@ AgeIndex,SqlDbType.Int);
planIndexParameter.Value =(对象)AgeItem.AgeIndex? DBNull.Value;
参数[0] = planIndexParameter;

下面是从 MSDN文档报价? 运营商解释该问题


  

要么first_ex pression和second_ex pression的类型必须是相同的,或隐式转换必须从一种类型到另


The following code gives an error - "No implicit conversion from DBnull to int."

SqlParameter[] parameters = new SqlParameter[1];    
SqlParameter planIndexParameter = new SqlParameter("@AgeIndex", SqlDbType.Int);
planIndexParameter.Value = (AgeItem.AgeIndex== null) ? DBNull.Value : AgeItem.AgeIndex;
parameters[0] = planIndexParameter;

解决方案

The problem is that the ?: operator cannot determine the return type because you are either returning an int value or a DBNull type value, which are not compatible.

You can of course cast the instance of AgeIndex to be type object which would satisfy the ?: requirement.

You can use the ?? null-coalescing operator as follows

SqlParameter[] parameters = new SqlParameter[1];     
SqlParameter planIndexParameter = new SqlParameter("@AgeIndex", SqlDbType.Int);
planIndexParameter.Value = (object)AgeItem.AgeIndex ?? DBNull.Value;
parameters[0] = planIndexParameter; 

Here is a quote from the MSDN documentation for the ?: operator that explains the problem

Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other.

这篇关于null分配到的SqlParameter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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