I often have the need to convert a null to a DBNull.Value for inserting into database, this function helps.
Introduction
Just a quick tip on a function that will handle all nullable types and make it easier to insert DBNull.Value
into the database.
Background
I posted a similar method a long while back in The Weird & the Wonderful and I needed it again today. However, today I made it better, by making it generic -- take all nullable types.
Using the Code
Here's the (Updated) Method
A commentor mentioned that I could still use ?? Operator.
I forgot, I could use the coalescence operator in the actual method so the method becomes only one line. Conciseness FTW!! For The Win!!
private Object convertDbNull<T>(T origValue){
if (origValue == null){
return System.DBNull.Value;
}
return origValue;
}
private Object convertDbNull<T>(T origValue){
return (Object)origValue ?? System.DBNull.Value;
}
Phew...this is the most time I've ever spent on a little tip/trick. 😆
Here's How You Can Use it
command.Parameters.AddWithValue("$screenName", convertDBNull(task.screenName));
Now if the value of task.screenName == null
, then it will be converted to DBNull.Value
.
However, if the value isn't null
, then the value will be returned and inserted into the database.
Template Code: Generics
Also, since the method takes any nullable type (String
s are nullable by default) like Int32
? or bool
? then the method will work with the type.
No more annoyances and worries about converting null
to DBNull.Value
.
Update - Someone Asked About ?? Operator
I had someone post a comment asking why the following wouldn't work:
command.Parameters.AddWithValue("$screenName", task.screenName ?? DBNull.Value);
That code uses the null
coalescing operator and it would be a very nice short-hand.
That is the exact code that I had hoped would work also. Alas, it does not compile.
Do you know why? Can you see why that code does not compile? It's not immediately obvious and you get a somewhat cryptic error that looks like:
Operator '??' cannot be applied to operands of type 'string' and 'DBNull'
It's attempting to indicate that you are comparing two different types (a string
and a dbnull
) and the compiler cannot do that on the null
coalescing operator.
You can fix that code by casting the String
as an object
with the following code:
command.Parameters.AddWithValue("$screenName", (object) task.screenName ?? DBNull.Value);
However, that is what my method does and again the method handles all types.
Maybe there were others who thought they could use the coalescing operator here too, and they were the ones who down-voted this article? Not sure, but this should clear this up.
History
- 9th March, 2023: Updated with info about using coalescing operator
- 26th February, 2023: First publication