How to resolve the SQLDateTime Overflow error in ASP.Net data class

By Joe Payne at March 01, 2009 13:06
Filed Under: AC7 Articles, Personal

I've been working alot with building data classes in ASP.Net.  While building some new tables, I ran into an odd problem.

The SQL table has 3 different datetime columns.  All are set as Nullable in SQL.  But whenever a new instance of my data class is saved, any datetime properties that were not assigned a value throw a SQL DateTime Overflow error exception.  Sure you can get around it by setting some default value, but I don't always want/need that.

Here's what I did to fix the error:

For the property data type, use Nullable(of DateTime) instead of just DateTime like this:

Private _CutoffDate As Nullable(Of DateTime)

<DataObjectField(
True, False, False)> _
Public Property CutoffDate() As Nullable(Of DateTime)

Get

Return Me._CutoffDate

End Get

Set(ByVal value As Nullable(Of DateTime))

If Me._CutoffDate <> value Then

Me._CutoffDate = value

Me.IsDirty = True

End If

End Set

End Property