如何清楚快速地使用DBNull.Value参数化空字符串

Dav*_*och 35 .net c# sql-server naming-conventions

我厌倦了编写以下代码:

/* Commenting out irrelevant parts
public string MiddleName;
public void Save(){
    SqlCommand = new SqlCommand();
    // blah blah...boring INSERT statement with params etc go here. */
    if(MiddleName==null){
        myCmd.Parameters.Add("@MiddleName", DBNull.Value);
    }
    else{
        myCmd.Parameters.Add("@MiddleName", MiddleName);
    }
    /*
    // more boring code to save to DB.
}*/
Run Code Online (Sandbox Code Playgroud)

所以,我写了这个:

public static object DBNullValueorStringIfNotNull(string value)
{
    object o;
    if (value == null)
    {
        o = DBNull.Value;
    }
    else
    {
        o = value;
    }
    return o;
}

// which would be called like:
myCmd.Parameters.Add("@MiddleName", DBNullValueorStringIfNotNull(MiddleName));
Run Code Online (Sandbox Code Playgroud)

如果这是一个很好的方法,那么你会建议什么作为方法名称?DBNullValueorStringIfNotNull有点冗长和令人困惑.

我也愿意完全缓解这个问题.我喜欢这样做:

myCmd.Parameters.Add("@MiddleName", MiddleName==null ? DBNull.Value : MiddleName);
Run Code Online (Sandbox Code Playgroud)

但这不起作用,因为"运营商'??' 不能应用于'string和'System.DBNull'"类型的操作数.

如果重要的话,我可以使用C#3.5和SQL Server 2005.

Ada*_*son 56

将您的任何一个值转换为object,然后编译.

myCmd.Parameters.Add("@MiddleName", MiddleName==null ? (object)DBNull.Value : MiddleName);
Run Code Online (Sandbox Code Playgroud)

  • 甜:`MiddleName?(对象)DBNull.Value`有效!或者更好的是`public static readonly object DBNullValue =(object)DBNull.Value;`with`MiddleName ?? DBNullValue`!你是我的英雄. (11认同)

Ser*_*y K 18

你可以避开显式的object使用SqlString.Null,而不是DBNull.Value:

MiddleName ?? SqlString.Null
Run Code Online (Sandbox Code Playgroud)

int,datetime等有相应的类型.这是一个包含更多示例的代码段:

 cmd.Parameters.AddWithValue("@StartDate", StartDate ?? SqlDateTime.Null);
 cmd.Parameters.AddWithValue("@EndDate", EndDate ?? SqlDateTime.Null);
 cmd.Parameters.AddWithValue("@Month", Month ?? SqlInt16.Null);
 cmd.Parameters.AddWithValue("@FormatID", FormatID ?? SqlInt32.Null);
 cmd.Parameters.AddWithValue("@Email", Email ?? SqlString.Null);
 cmd.Parameters.AddWithValue("@ZIP", ZIP ?? SqlBoolean.Null);
Run Code Online (Sandbox Code Playgroud)


Chr*_*sic 11

就个人而言,这就是我对扩展方法所做的事情(确保它进入静态类)

public static object GetStringOrDBNull(this string obj)
{
    return string.IsNullOrEmpty(obj) ? DBNull.Value : (object) obj
}
Run Code Online (Sandbox Code Playgroud)

然后你就拥有了

myCmd.Parameters.Add("@MiddleName", MiddleName.GetStringOrDBNull());
Run Code Online (Sandbox Code Playgroud)

  • 看看你是否改变主意,而不是拥有100个if语句,你有100个三元运算符. (4认同)
  • 我实际上使用的是空合并运算符.你必须同意`MiddleName ?? DBNullValue`非常简单.但是你的评论也是+1. (2认同)

ham*_*uri 6

myCmd.Parameters.Add("@MiddleName", MiddleName ?? (object)DBNull.Value);
Run Code Online (Sandbox Code Playgroud)