我有以下代碼來指定SQL查詢的參數。當我使用Code 1
;但使用Code 2
時效果很好。在Code 2
我們有一個空的檢查,因此if..else
塊。AddWithValue參數爲NULL時出現異常
例外:
的參數化查詢 '(@application_ex_id nvarchar的(4000))選擇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);
}
QUESTION
您能解釋爲什麼它不能從代碼1中的logSearch.LogID值中獲取NULL(但能夠接受DBNull)?
有沒有更好的代碼來處理呢?
參考:
- Assign null to a SqlParameter
- Datatype returned varies based on data in table
- Conversion error from database smallint into C# nullable int
- 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;
}
你是什麼意思更好?代碼2是向數據庫發送空值的正確方法。 –
參考:http://stackoverflow.com/questions/13265704/conversion-error-from-database-smallint-into-c-sharp-nullable-int – Lijo