seaN aitkeN – The Blog

July 14, 2006

Nullable datetime database columns… can we say DateTime?

Filed under: .NET — clevercoder @ 12:30 pm

I’m always trying to either re-invent the wheel, or at least make my code more efficient and readable.. or just cool. Struggling with the DBNull values returned from ADO data providers in .NET has always been slightly less than exciting. Problems always tend to creep up when you least expect them to. Recently, I encountered a situation where I wanted to simply read a very nullable datetime column in SQL Server to a Nullable object in .NET. Using strongly typed datasets lead me to think that this should be easily achieved. Was I wrong.. Although this simply is useless with strongly typed datasets (as accessing a DateTime column of a typed DataRow will always throw an exception), it’s still a neat trick that can be adapted for other use.

I was on a search to simplify the mundane task of assigning the value of a nullable datetime column in SQL Server to a Nullable<DateTime> object in .NET. This is what I started with:

obj.SomeDateField = (row["SomeDateField"] == DBNull)?null:(DateTime)row["SomeDateField"];

Writing this dozens of times over and over gets old. Real quicK! In reference to the mention of strongly typed datasets above, this is the alternative using them:

if (row.IsSomeDataFieldNull())
{
     obj.SomeDateField = null;
}
else
{
     obj.SomeDateField = row.SomeDateField;
}

Far from simple. So I got to thinking.. “There must be an easier way to do this!”..

In a nutshell, I created the following method for working with a cell returned from a DataRow to create a Nullable type that can be specified at runtime:

public static Nullable ToNullable(object dbSource) where T : struct
        {

Nullable retVal;

if (DBNull.Value == dbSource)
            {
                retVal = null;
            }
            else
            {
                retVal = (T?) dbSource;
            }

return retVal;
        }

And, using this trick, the example above would look like:

obj.SomeDateField = DBHelper.ToNullable<datetime>(row["SomeDateField"]);

Cheers!


1 Comment »

  1. http://www.Colours.sblinks.net

    Nullable datetime database columns… can we say DateTime? | seaN aitkeN – The Blog

    Trackback by www.Colours.sblinks.net — November 3, 2023 @ 11:52 pm


RSS feed for comments on this post. TrackBack URI

Leave a comment

Create a free website or blog at WordPress.com.