我如何参数化一个空字符串的DBNull.Value清晰,快速地 [英] How do I Parameterize a null string with DBNull.Value clearly and quickly

查看:296
本文介绍了我如何参数化一个空字符串的DBNull.Value清晰,快速地的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我厌倦了写下面的code的:

I got tired of writing the following code:

/* 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.
}*/

所以,我写这样的:

So, I wrote this:

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

如果这是一个很好的方式去这样做,然后你会建议作为方法名? DBNullValueorStringIfNotNull 的是一个有点冗长和混乱。

If this is a good way to go about doing this then what would you suggest as the method name? DBNullValueorStringIfNotNull is a bit verbose and confusing.

我也开来的方式来完全缓解这一问题。我很乐意这样做:

I'm also open to ways to alleviate this problem entirely. I'd LOVE to do this:

myCmd.Parameters.Add("@MiddleName", MiddleName==null ? DBNull.Value : MiddleName);

但不会工作,因为操作?不能应用于类型的操作数串和'System.DBNull'

but that won't work because the "Operator '??' cannot be applied to operands of type 'string and 'System.DBNull'".

我已经在我手上了C#3.5和SQL Server 2005,如果它很重要。

I've got C# 3.5 and SQL Server 2005 at my disposal if it matters.

推荐答案

演员要么你的价值观,以对象键,它会编译。

Cast either of your values to object and it will compile.

myCmd.Parameters.Add("@MiddleName", MiddleName==null ? (object)DBNull.Value : MiddleName);

这篇关于我如何参数化一个空字符串的DBNull.Value清晰,快速地的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆