AddWithValue参数为NULL时的异常

LCJ*_*LCJ 76 .net c# ado.net

我有以下代码来指定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);
Run Code Online (Sandbox Code Playgroud)

代码2:

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

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

  2. 有没有更好的代码来处理这个?

参考:

  1. 将null分配给SqlParameter
  2. 返回的数据类型因表中的数据而异
  3. 从数据库smallint到C#nullable 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;
    }
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 131

烦人,不是吗

您可以使用:

command.Parameters.AddWithValue("@application_ex_id",
       ((object)logSearch.LogID) ?? DBNull.Value);
Run Code Online (Sandbox Code Playgroud)

或者,使用像"小巧玲珑"这样的工具,它会为你做所有麻烦.

例如:

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

很想添加一种方法来获得IDataReader......但不确定它是否是一个好主意.

  • @Lijo因为参数值中的"null"表示"不发送此参数".我怀疑这是一个糟糕的决定,只是被烘焙了.事实上,我认为**大多数的'DBNull`是一个根本不好的决定,它已被烘焙:http://stackoverflow.com/a/9632050/23354 (16认同)
  • @Phil嗯,是的,我明白你的意思......也许`AddWithValueAndTreatNullTheRightDamnedWay(...)` (4认同)

Axi*_*xus 43

我发现为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);
}
Run Code Online (Sandbox Code Playgroud)

然后你就像这样称呼它:

sqlCommand.Parameters.AddWithNullableValue(key, value);
Run Code Online (Sandbox Code Playgroud)

  • 我读了Marc的答案并且想"我觉得我只想为参数集合编写一个扩展方法",然后我向下滚动一个头发......(扩展方法的好处是我可以做一个查找/替换之后和我的所有代码更新完成) (2认同)
  • 也许我错了(有点像 C# 新手)但你不能像这样更简洁地做到这一点:`return collection.AddWithValue(parameterName, value ?? DBNull.Value);` (2认同)