在添加sqlCommands的参数时,我需要为每个空值使用Convert.DBNull。这很乏味,因为我有很多sql命令。因此,只要将此Object(Convert.DBNull)设置为参数,只要它获取null值作为参数,就会容易得多。
示例:我有这样的代码:
cmd.Parameters.AddWithValue("@MasterLastModifiedBy", Master.LastModifiedBy);
由于像Master.LastModifiedBy这样的变量有时可能为null,因此我必须将其重新格式化为:
cmd.Parameters.AddWithValue("@MasterLastModifiedBy", Master.LastModifiedBy?? Convert.DBNull);
我不想在所有参数中重新格式化。那么,我还能做些什么来解决这个问题呢?
我建议使用某种ORM库。 Dapper或Entity Framework将是一个很好的起点。
或者您可以编写自己的方法来为每个参数添加空检查。
最后(具体地)考虑最后修改日期,你总是可以设置它,这可能会简化一堆查询
编辑:
您的扩展方法可能如下所示:
public static class SqlExtensions // needs to be in a static class
{
public static void AddWithValueAndNullCheck(this SqlParameterCollection collection, string parameterName, object value)
{
if (object == null)
{
collection.AddWithValue(parameterName, DBNull.Value);
}
else
{
collection.AddWithValue(parameterName, value);
}
}
}