Tôi có mã sau để chỉ định các tham số cho truy vấn SQL. Tôi nhận được ngoại lệ sau khi tôi sử dụng Code 1
; nhưng hoạt động tốt khi tôi sử dụng Code 2
. Trong Code 2
chúng tôi có một kiểm tra cho null và do đó một if..else
khối.
Ngoại lệ:
Truy vấn được tham số hóa '(@application_ex_id nvarchar (4000)) SELECT E.application_ex_id A' yêu cầu tham số '@application_ex_id' không được cung cấp.
Mã 1 :
command.Parameters.AddWithValue("@application_ex_id", logSearch.LogID);
Mã 2 :
if (logSearch.LogID != null)
{
command.Parameters.AddWithValue("@application_ex_id", logSearch.LogID);
}
else
{
command.Parameters.AddWithValue("@application_ex_id", DBNull.Value );
}
CÂU HỎI
Bạn có thể vui lòng giải thích tại sao nó không thể lấy NULL từ giá trị logSearch.LogID trong Mã 1 (nhưng có thể chấp nhận DBNull) không?
Có mã nào tốt hơn để xử lý điều này không?
Tham khảo :
- Gán null cho một SqlParameter
- Loại dữ liệu được trả về thay đổi tùy theo dữ liệu trong bảng
- Lỗi chuyển đổi từ cơ sở dữ liệu smallint thành C # nullable int
- Điểm của DBNull là gì?
MÃ
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;
}