如何指定在 c# 中的原始参数为 null 时自动使用 Convert.DBNull 作为 sql 参数值



我需要对每个空值使用 Convert.DBNull,同时添加 sqlCommand 的参数。这很乏味,因为我有很多 sql 命令。因此,如果有任何方法可以将此对象(Convert.DBNull)设置为参数,每当它获得空值作为参数时,都会容易得多。

例:我有这样的代码:

cmd.Parameters.AddWithValue("@MasterLastModifiedBy", Master.LastModifiedBy);

由于像Master.LastModifiedBy这样的变量有时可能是空的,因此我必须将其重新格式化为:

cmd.Parameters.AddWithValue("@MasterLastModifiedBy", Master.LastModifiedBy?? Convert.DBNull);

我不想在所有参数中进行这种重新格式化。那么,我还能做些什么来解决这个问题呢?

我建议使用某种ORM库。Dapper 或实体框架将是很好的起点。

或者,您可以编写自己的方法来为每个参数添加 null 检查。

最后(具体)考虑上次修改日期,您可以随时设置它,这可能会简化一堆查询

编辑:

扩展方法可能如下所示:

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);
        }
    }
}

相关内容

最新更新