C# ADO.NET: nulls and DbNull — is there more efficient syntax?

后端 未结 6 2055
时光取名叫无心
时光取名叫无心 2020-12-14 00:03

I\'ve got a DateTime? that I\'m trying to insert into a field using a DbParameter. I\'m creating the parameter like so:

DbParameter         


        
相关标签:
6条回答
  • 2020-12-14 00:30

    If you're using C# 3.0 you can create an extension method to do this easy:

    public static class DBNullableExtensions
    {
        public static object ToDBValue<T>(this Nullable<T> value) where T:struct
        { 
            return value.HasValue ? (object)value.Value : DBNull.Value;
        }
    }
    
    
    class Program
    {
        static void Main(string[] args)
        {
            int? x = null;
    
            Console.WriteLine(  x.ToDBValue() == DBNull.Value );
        }
    }
    
    0 讨论(0)
  • 2020-12-14 00:32

    If you are using SQLServer, the System.Data.SqlTypes namespace contains some utility classes that avoid the annoying type casting. For example instead of this:

    var val = (object) "abc" ?? DBNull.Value;
    

    you can write this:

    var val = "abc" ?? SqlString.Null;
    
    0 讨论(0)
  • 2020-12-14 00:45

    Ah ha! I found an even more efficient solution than @Trebz's!

    datePrm.Value = nullableDate ?? (object)DBNull.Value;
    
    0 讨论(0)
  • 2020-12-14 00:45

    The way that I do it, is I have a static utility class that just goes through and checks to see if the parameter value is null, then i set the value to do DBNull. I just do that before i call the Execute.

    0 讨论(0)
  • 2020-12-14 00:52

    It would work if you used

    datePrm.Value = nullableDate.HasValue ? (object)nullableDate.Value : DBNull.Value;
    
    0 讨论(0)
  • 2020-12-14 00:56

    I think the error with your second attempt is due to nullableDate.Value and DBNull.Value being different types and the ternary operator needing to pick one type to return in both cases. I don't have the environment to test this but I think this should work for you:

    datePrm.Value = nullableDate.HasValue ? (object)nullableDate.Value : (object)DBNull.Value;
    
    0 讨论(0)
提交回复
热议问题