我有以下代码用于指定 SQL 查询的参数。我使用时遇到以下异常Code 1
;但当我使用时效果很好Code 2
. In Code 2
我们检查是否为空,因此if..else
block.
例外:
参数化查询“(@application_ex_id nvarchar(4000))SELECT E.application_ex_id A”需要参数“@application_ex_id”,但未提供该参数。
Code 1:
command.Parameters.AddWithValue("@application_ex_id", logSearch.LogID);
Code 2:
if (logSearch.LogID != null)
{
command.Parameters.AddWithValue("@application_ex_id", logSearch.LogID);
}
else
{
command.Parameters.AddWithValue("@application_ex_id", DBNull.Value );
}
QUESTION
您能否解释一下为什么无法从代码1中的logSearch.LogID值中获取NULL(但能够接受DBNull)?
有更好的代码来处理这个问题吗?
参考:
- 将 null 分配给 SqlParameter
- 返回的数据类型根据表中的数据而变化
- 从数据库 Smallint 到 C# nullable int 的转换错误
-
DBNull 有什么意义?
CODE
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;
}
很烦人,不是吗。
您可以使用:
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();
I'm tempted向 dapper 添加一个方法来获取IDataReader
...还不太确定这是否是一个好主意。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)