null分配到的SqlParameter

编程入门 行业动态 更新时间:2024-10-22 20:33:32
本文介绍了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

本文发布于:2023-11-30 01:25:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648256.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:分配   null   SqlParameter

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!