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);
코드 2 :
if (logSearch.LogID != null)
{
command.Parameters.AddWithValue("@application_ex_id", logSearch.LogID);
}
else
{
command.Parameters.AddWithValue("@application_ex_id", DBNull.Value );
}
질문
코드 1의 logSearch.LogID 값에서 NULL을 가져올 수없는 이유를 설명해 주시겠습니까 (DBNull 허용 가능)?
이것을 처리하는 더 좋은 코드가 있습니까?
참조 :
- SqlParameter에 null 할당
- 반환되는 데이터 유형은 테이블의 데이터에 따라 다릅니다.
- 데이터베이스 smallint에서 C # nullable int 로의 변환 오류
- 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;
}