强制转换为(对象)的DBNull返回不同的值 [英] DBNull cast to (object) returns different value

查看:148
本文介绍了强制转换为(对象)的DBNull返回不同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用 Parameters.AddWithVallue 编写 DBNull.Value 时使用一个可选参数(一个<$ c C#方法的$ c> string )为 null

I am trying to write DBNull.Value using Parameters.AddWithVallue when an optional parameter (a string) of a C# method is null.

public static void Abc(string distrito, string municipio = null)

command.Parameters.AddWithValue("@Municipio", municipio ?? (object)DBNull.Value);
command.Parameters.AddWithValue("@Municipio", municipio.Length > 0 ? municipio : (object)DBNull.Value);

但是,(对象)DBNULL 返回两个以两种不同的工作方式方式使用不同的值。一个写为空/空,其他写为NULL。

However, (object)DBNULL returns two different values in two different working ways. One writes empty/null and other NULL.

推荐答案

我要作一些假设,但我想我知道这是怎么回事。 municipio 可能是一个空字符串。它是 not null。

I'm going to make a few assumptions, but I think I know what's going on. municipio is probably an empty string. It is not null.

在这种情况下, municipio? (object)DBNull.Value 为空字符串,不是为空。但是, municipio.Length> 0? municipio:(对象)DBNull.Value 的值为 DBNull.Value ,它将在SQL Server中生成一个null。在这种情况下,如果 municipio 为null,则将抛出此代码。既然您说的是代码运行,我就假设 municipio 不为空。

In that case, municipio ?? (object)DBNull.Value will be an empty string, not null. However, municipio.Length > 0 ? municipio : (object)DBNull.Value has a value of DBNull.Value, which will generate a null in SQL Server. In this case, if municipio is null, then this code will throw. Since you say the code runs, I'm assuming that municipio is not null.

这篇关于强制转换为(对象)的DBNull返回不同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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