首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >当AddWithValue参数为空时出现异常

当AddWithValue参数为空时出现异常
EN

Stack Overflow用户
提问于 2012-11-19 17:40:29
回答 4查看 69.7K关注 0票数 96

我有以下代码来指定SQL查询的参数。当我使用Code 1时,我得到了以下异常;但当我使用Code 2时,它工作得很好。在Code 2中,我们会检查null,因此也会检查if..else块。

例外:

应用程序参数化查询'(@application_ex_id nvarchar(4000))SELECT应用程序A‘需要参数’@

_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值中获取空值(但可以接受DBNull)吗?
  2. 有没有更好的代码来处理这个问题?

参考

  1. Assign null to a SqlParameter
  2. Datatype returned varies based on data in table
  3. Conversion error from database smallint into C# nullable int
  4. What is the point of 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;
    }
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2012-11-19 17:43:33

很烦人,不是吗。

您可以使用:

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...我还不确定这是不是一个好主意。

票数 160
EN

Stack Overflow用户

发布于 2014-08-22 08:26:13

我发现只需为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);
票数 54
EN

Stack Overflow用户

发布于 2015-10-23 21:57:40

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

SQL:

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

C#:

int? myvalue = initMyValue();
if (myvalue.hasValue) cmd.Parameters.AddWithValue("myparamater", myvalue);
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13451085

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档