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

How to specify to use Convert.DBNull automatically as sql parameter value when the original parameter is null in c#?

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

示例: 我有这样的代码:

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

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

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

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

我建议使用 ORM Library of some sort. Dapper or 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);
        }
    }
}