AddWithValue参数为NULL时发生异常


89

我有以下代码用于指定SQL查询的参数。我在使用时遇到了异常Code 1;但是我使用时工作正常Code 2。在这里,Code 2我们检查是否为null,因此是否为if..else块。

例外:

参数化查询'{@application_ex_id nvarchar(4000))SELECT E.application_ex_id A'期望未提供参数'@application_ex_id'。

代码1

command.Parameters.AddWithValue("@application_ex_id", logSearch.LogID);

代码2

if (logSearch.LogID != null)
{
         command.Parameters.AddWithValue("@application_ex_id", logSearch.LogID);
}
else
{
        command.Parameters.AddWithValue("@application_ex_id", DBNull.Value );
}

  1. 您能否解释一下为什么它无法从代码1中的logSearch.LogID值中获取NULL(但能够接受DBNull)?

  2. 有更好的代码来处理吗?

参考

  1. 将空值分配给SqlParameter
  2. 返回的数据类型因表中的数据而异
  3. 从数据库smallint到C#可为空的int的转换错误
  4. DBNull的意义是什么?

    public Collection<Log> GetLogs(LogSearch logSearch)
    {
        Collection<Log> logs = new Collection<Log>();

        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();

            string commandText = @"SELECT  *
                FROM Application_Ex E 
                WHERE  (E.application_ex_id = @application_ex_id OR @application_ex_id IS NULL)";

            using (SqlCommand command = new SqlCommand(commandText, connection))
            {
                command.CommandType = System.Data.CommandType.Text;

                //Parameter value setting
                //command.Parameters.AddWithValue("@application_ex_id", logSearch.LogID);
                if (logSearch.LogID != null)
                {
                    command.Parameters.AddWithValue("@application_ex_id", logSearch.LogID);
                }
                else
                {
                    command.Parameters.AddWithValue("@application_ex_id", DBNull.Value );
                }

                using (SqlDataReader reader = command.ExecuteReader())
                {
                    if (reader.HasRows)
                    {
                        Collection<Object> entityList = new Collection<Object>();
                        entityList.Add(new Log());

                        ArrayList records = EntityDataMappingHelper.SelectRecords(entityList, reader);

                        for (int i = 0; i < records.Count; i++)
                        {
                            Log log = new Log();
                            Dictionary<string, object> currentRecord = (Dictionary<string, object>)records[i];
                            EntityDataMappingHelper.FillEntityFromRecord(log, currentRecord);
                            logs.Add(log);
                        }
                    }

                    //reader.Close();
                }
            }
        }

        return logs;
    }

3
更好意味着什么?代码2是将空值发送到数据库的正确方法。
菲尔·甘

Answers:


148

烦人的,不是吗。

您可以使用:

command.Parameters.AddWithValue("@application_ex_id",
       ((object)logSearch.LogID) ?? DBNull.Value);

或者,使用“ dapper”之类的工具,它将为您解决所有麻烦。

例如:

var data = conn.Query<SomeType>(commandText,
      new { application_ex_id = logSearch.LogID }).ToList();

很想在dapper中添加一个方法来获取IDataReader...尚不确定是否是个好主意。


1
我当时正在考虑对该Parameters物业进行扩展-是Object吗?
菲尔·甘

6
@Phil hmmm,是的,我明白你的意思了……也许AddWithValueAndTreatNullTheRightDamnedWay(...)
Marc Gravell

1
@MarcGravell您能否解释一下为什么它无法从代码1中的logSearch.LogID值中获取NULL(但能够接受DBNull)?
LCJ 2012年

18
@Lijo,因为null在参数值中表示“请勿发送此参数”。我怀疑这是一个错误的决定,那简直是在烤其实,我觉得,大多数DBNull是,得到了在烤根本错误的决定:stackoverflow.com/a/9632050/23354
马克Gravell

1
@tylerH,因为无效的强制转换规则-在C#9中可能会变弱
Marc Gravell

52

我发现为编写一个用于SqlParameterCollection处理空值的扩展方法会更容易:

public static SqlParameter AddWithNullableValue(
    this SqlParameterCollection collection,
    string parameterName,
    object value)
{
    if(value == null)
        return collection.AddWithValue(parameterName, DBNull.Value);
    else
        return collection.AddWithValue(parameterName, value);
}

然后,您可以这样称呼它:

sqlCommand.Parameters.AddWithNullableValue(key, value);

可以是int或int?,string,bool或bool?,DateTime或Datetime?等等?
Kiquenet

3
我读了Marc的回答,然后想:“我想我只想为Parameters集合编写一个扩展方法”,然后我向下滚动一卷...(关于扩展方法的妙处是,我可以执行一次查找/替换操作之后,并且我所有的代码更新都完成了)
jleach'1

1
很好的解决方案...扩展方法必须在静态类中定义。如何:实现和调用自定义扩展方法
Chris Catignani

2
也许我弄错了(有点像C#新手),但您不能这样更简洁地做到这一点:return collection.AddWithValue(parameterName, value ?? DBNull.Value);
Tobias Feil

1
@TobiasFeil是的,您也可以这样做。这只是一个品味问题。
AxiomaticNexus,

4

以防万一您在调用存储过程时这样做:我认为如果在参数上声明默认值并仅在必要时添加它,则更容易阅读。

SQL:

DECLARE PROCEDURE myprocedure
    @myparameter [int] = NULL
AS BEGIN

C#:

int? myvalue = initMyValue();
if (myvalue.hasValue) cmd.Parameters.AddWithValue("myparamater", myvalue);

0

一些问题,允许与必要设置SQLDbType

command.Parameters.Add("@Name", SqlDbType.NVarChar);
command.Parameters.Value=DBNull.Value

您键入SqlDbType.NVarChar的位置。必需设置SQL类型。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.