将空值发送到数据库

Send null values to the DB

我正在从 xml 中获取 "SystemID" 的值。也就是说,我将值存储在 dictionary<string,string>, 中,如果 xml 中未提供 "SystemID",我想将 null 发送到数据库,即 <SystemID></SystemID> xml.

中不存在

这是我的代码。但它不起作用。任何想法!

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

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.

如果它不在字典中,您将在 string.IsNullOrEmpty(attributeValues["systemID"]) 上得到一个 KeyNotFoundException,因此假设问题不在您的数据库中,即目标列允许 NULL,您可以:

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

这将在尝试获取其值之前检查您的字典是否具有您的键,从而防止该异常,如果该键不存在,它将分配 null。

XML 标签区分大小写。修改代码为 attributeValues["SystemID"]