0

I am fetching the values of "SystemID" from an xml. i.e. I am storing the values in a dictionary<string,string>, I want to send null to the DB if the "SystemID" was not supplied in the xml i.e. the <SystemID></SystemID> was not present in the xml.

Here is my code. But it's not working. Any Ideas!

sqlCommand.Parameters.Add("@SystemID", SqlDbType.Int).Value = string.IsNullOrEmpty(attributeValues["systemID"]) ? (object)DBNull.Value : Convert.ToInt32(attributeValues["systemID"]);
Ninja
  • 331
  • 1
  • 3
  • 16

2 Answers2

1

The <systemID> may or may not be present in the xml.If it is not in xml then obviously it will not be in the dictionary. Then in that case i want to assign null to the DB.

If it won't be in the dictionary, you will get a KeyNotFoundException on string.IsNullOrEmpty(attributeValues["systemID"]), so assuming the problem is not in your database i.e. the target column allows NULL, you can:

sqlCommand.Parameters.Add("@SystemID", SqlDbType.Int).Value =
    attributeValues.ContainsKey("systemID") ?
    Convert.ToInt32(attributeValues["systemID"]) :
    (object)DBNull.Value;

This would check if your dictionary has your key before trying to get its value, preventing that exception, and if the key does not exist, it will assign null.

Saeb Amini
  • 23,054
  • 9
  • 78
  • 76
0

XML tags are Case-sensitive . modify the code to attributeValues["SystemID"]

Nikita Shrivastava
  • 2,978
  • 10
  • 20