cmd.Parameters.AddWithValue nullable int

后端 未结 3 1617
后悔当初
后悔当初 2021-01-25 08:07

In my data layer class, I initialize a parameter like so:

private int? _DependencyID;

public int? DependencyID
{ get {return _DependencyID;} set {_DependencyID          


        
相关标签:
3条回答
  • 2021-01-25 08:54

    You need to add an object:

    cmd.AddWithValue("@DependencyID", _DependencyID == null? DBNull.Value : (object)_DependencyID); 
    

    You can shorten that to

    cmd.AddWithValue("@DependencyID", (object)_DependencyID ?? DBNull.Value); 
    
    0 讨论(0)
  • 2021-01-25 09:00

    I have created an extension to simply the code.

    public static class SQLExtension
    {
        public static SqlParameter AddWithNullable<T>(
            this SqlParameterCollection collection, 
            string parameterName, 
            Nullable<T> value) where T : struct, IComparable
        {
            return collection.AddWithValue(
                parameterName, (value.HasValue ? value.Value : (object)DBNull.Value)
            );
        }
    }
    

    Here is how you can use it.

    cmd.AddWithNullable("@DependencyID", _DependencyID);
    
    0 讨论(0)
  • 2021-01-25 09:05

    AFAIC, ADO.NET/SQL don't support nullable types this way.

    The last example looks closest to correct to me. What kind of issues are you having with it? If you are just getting a compile error related to types, type cast your value to object:

    (object)DependencyID.Value;
    

    Since both values on either side of : must be of the same type.

    0 讨论(0)
提交回复
热议问题