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

后端 未结 6 2073
时光取名叫无心
时光取名叫无心 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: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;
    

提交回复
热议问题