मेरे पास SQL क्वेरी के लिए पैरामीटर निर्दिष्ट करने के लिए निम्न कोड है। जब मैं Code 1
का उपयोग करता हूं तो मुझे निम्नलिखित अपवाद मिल रहा है; लेकिन जब मैं Code 2
का उपयोग करता हूं तो ठीक काम करता है। Code 2
में हमारे पास शून्य के लिए एक चेक है और इसलिए if..else
ब्लॉक है।अपवाद जब AddWithValue पैरामीटर NULL
अपवाद:
पैरामिट्रीकृत क्वेरी '(@application_ex_id nvarchar (4000)) का चयन E.application_ex_id ए' पैरामीटर '@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 में लॉगऑर्च.लोगिड मान से न्यूल क्यों नहीं ले पा रहा है (लेकिन डीबीएनयूएल को स्वीकार करने में सक्षम)?
क्या इसे संभालने के लिए कोई बेहतर कोड है?
संदर्भ:
- 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