NHibernate.HibernateException SqlDateTime overflow

Working on a project based on the wonderful Sharp Architecture, I’ve noticed that under some circumstances, creating and saving an instance of an object which has DateTime members raised an exception like this one,

NHibernate.HibernateException SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.

Here is a sample code, where I just change the customer name.

Let’s suppose I have Customer persistence class, which is defined as,

public class Customer : Entity

{   #region Members

public virtual string Name { get; set; }

public virtual DateTime Birthday { get; set; }

#endregion Members

}

Now, get our first Customer and change his Name,

Customer cust = customerRepository.Get(1);

customerRepository.DbContext.BeginTransaction();

cust.Name = “John”;

customerRepository.SaveOrUpdate(cust);

customerRepository.DbContext.CommitTransaction();

Quick Solution: Change the DateTime fiel to null able adding a ? sign. So, the Birthday declaration should be like this,

public virtual DateTime? Birthday { get; set; }

In order to know the reason of this issue, please refer to this great explanation at http://barchitect.blogspot.com/2009/07/nhibernate-sqldatetime-overflow-issue.html