Is it possible to coalesce string and DBNull in C#?

前端 未结 10 1297
滥情空心
滥情空心 2021-01-02 06:24

I\'m writing a C# routine to call a stored proc. In the parameter list I\'m passing in, it is possible that one of the values can legally be null. So I thought I\'d use a

相关标签:
10条回答
  • 2021-01-02 06:32

    Not like that, no. The types have to match. The same is true for the ternary.

    Now, by "match", I don't mean they have to be the same. But they do have to be assignment compatible. Basically: in the same inheritance tree.

    One way to get around this is to cast your string to object:

    var result = (object)stringVar ?? DBNull.Value;
    

    But I don't like this, because it means you're relying more on the SqlParameter constructor to get your types right. Instead, I like to do it like this:

    cmd.Parameters.Add("@theParam", SqlDbTypes.VarChar, 50).Value = theParam;
    // ... assign other parameters as well, don't worry about nulls yet
    
    // all parameters assigned: check for any nulls
    foreach (var p in cmd.Parameters) 
    { 
        if (p.Value == null) p.Value = DBNull.Value; 
    }
    

    Note also that I explicitly declared the parameter type.

    0 讨论(0)
  • 2021-01-02 06:36

    Not sure the specific answer to your question, but how about this?

    string.IsNullOrEmpty(theParam) ? DBNull.Value : theParam
    

    or if blank is ok

    (theParam == null) ? DBNull.Value : theParam
    
    0 讨论(0)
  • 2021-01-02 06:38

    cmd.Parameters.Add(new SqlParameter("@theParam", (theParam == null) ? DBNull.Value : theParam));

    0 讨论(0)
  • 2021-01-02 06:41

    In your stored proc when you declare the incoming variable, have it set the var equal to null and then do not pass it in from your csharp code, it will then pick up the default value from sql

    @theParam as varchar(50) = null
    

    and then in your csharp

    if (theParam != null)
        cmd.Parameters.Add(new SqlParameter("@theParam", theParam));
    

    This is how I usually pass option and/or defaulted values to my stored procs

    0 讨论(0)
  • 2021-01-02 06:42

    The ?? operator returns the left-hand operand if it is not null, or else it returns the right operand. But in your case they are different types, so it doesn't work.

    0 讨论(0)
  • 2021-01-02 06:45

    The Null Coalesce operator only with with data of the same type. You cannot send NULL to the SqlParamater as this will make Sql Server says that you didn't specify the parameter.

    You can use

    new SqlParameter("@theParam", (object)theParam ?? (object)DBNull.Value)
    

    Or you could create a function that return DBNull when null is found, like

    public static object GetDataValue(object o)
    {
        if (o == null || String.Empty.Equals(o))
            return DBNull.Value;
        else
            return o;
    }
    

    And then call

    new SqlParameter("@theParam", GetDataValue(theParam))
    
    0 讨论(0)
提交回复
热议问题