null分配到的SqlParameter [英] Assign null to a 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 anint
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 followsSqlParameter[] 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 problemEither 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屋!