我有以下代码来指定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中的logSearch.LogID值中获取NULL(但能够接受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......但不确定它是否是一个好主意.
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)
| 归档时间: |
|
| 查看次数: |
52998 次 |
| 最近记录: |