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

后端 未结 6 2077
时光取名叫无心
时光取名叫无心 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(this Nullable 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 );
        }
    }
    

提交回复
热议问题