I recently took on the project of trying to create my own Business Logic Layer (BLL) and Data Access Layer (DAL) in a personal web project so I could understand how the various layers of n-tier architecture are supposed to work. I didn’t get very far before I realized that allowing NULL database values (System.DBNull.Value) in various fields in my database was going to give me a large headache
After doing a lot of research, I didn’t come-up with too many satisfactory methods for dealing with DBNulls. At best, it seemed like I’d have to write all sorts of methods for converting DBNulls to either a default value for each data type (I.e., define an integer to default to zero, a string defaults to String.Empty, a date defaults to DateTime.MinValue, etc.) or use the new VB.NET 2.0 Nullable Types and set each data type to Nothing. This sounded like a lot of work and a lot of code… more code = more errors!
I read a few articles on using Generic Types in VB.NET 2.0 and it appeared to me as though they could be the answer to my prayers: Create one generic method that can check for DBNulls for all data types. A blog post by Saravana Kumar shows a way to accomplish this using C#. However, C# has a keyword default which doesn’t exist in VB.NET (at least not that I could find.) This keyword apparently returns the default value for each data type, just like I wanted!
After much tinkering, here is what I came-up after trying to convert Saravana’s code to VB.NET:
Public Shared Function ConvertDBNull(Of T)(ByVal obj As Object) As T If (obj Is System.DBNull.Value) Then obj = Nothing End If Return CType(obj, T)End Function
So far, it seems to work! For example, with the following code:
Dim oSomeTestObject As Object = System.DBNull.ValueDim strResult As String = ConvertDBNull(Of Integer)(oSomeTestObject)
The value of strResult is returned as a zero. Another example:Dim oSomeTestObject As Object = System.DBNull.ValueDim strResult As String = ConvertDBNull(Of Date)(oSomeTestObject)
The value of strResult is returned as a “12:00:00 AM”. For most dates that I display, I always format them as MM/dd/yyyy, so a date value only exposing time won't show.
I tested this new method on my BLL, and so far it works great! w00t! If you have a better method for dealing with DBNulls in your Business Logic, let me know… I’m all ears!