tags:

views:

287

answers:

3

Hello there,

I have a [DataContract] called ReportRequest with a NOT NULL column 'SubmittedAt'. So my DataContract looks something like:

[DataContract]
public class ReportRequest
{
    Int32 templateId;
    DateTime submittedAt = DateTime.Now;

    [DataMember]
    public virtual Int32? Id
    {
        get;
        set;
    }

    public virtual DateTime SubmittedAt
    {
        get {
              return submittedAt; 
        }
        set
        {
            submittedAt = value; 
        }
    }
}

Because, I have taken a private variable submittedAt and is initialised with DateTime.Now,

shouldn't the SubmittedAt property have the same value??

But when i am calling NHibernate

session.Save(objReportRequest);

I am getting the error:

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

Any thoughts why I am getting this error?

As a workaround for now I have changed getter for SubmittedAt property as:

        get {
            if (submittedAt == DateTime.MinValue)
                return DateTime.Now;
            else
                return submittedAt; 
        }
A: 

It's because DateTime.MinValue doesn't have the same meaning as the minimum value you could store in a SQL Server datetime column. In SQL server datetime column the minimum date you could store is the one you get in your exception stack. It is SqlDateTime.MinValue

Darin Dimitrov
Thanks to all for your reply. I understand that SQL Server Min. Date Value is different from CLR DateTime.MinValue. But what I am confused about is what does following statement means to NHibernate: DateTime submittedAt = DateTime.Now; or it just ignores my setting of DateTime.Now ?
inutan
IMHO this is because the way you call your web service. Even that you set `submittedAt = DateTime.Now` if the caller of the web service doesn't explicitly set a date the xml serializer will explicitly call the setter and put `DateTime.MinValue`.
Darin Dimitrov
+3  A: 

SQL Server minimum DateTime value is bigger than DateTime.Min value. So you cannot save minimum value to database.

Marek Tihkan
Even I don't want to, that's why I am initialising the property with DateTime.Now
inutan
+1  A: 

As Marek Tihkan already said: SqlServer can not store the DateTime.MinValue, it is outside of the value range of SqlServer's DateTime data type.

The best advise is to use nullable types anyway:

[DataContract]
public class ReportRequest
{
    DateTime? submittedAt = null;

    public virtual DateTime? SubmittedAt
    {
        get {
              return submittedAt; 
        }
        set
        {
            submittedAt = value; 
        }
    }
}

By SubmittedAt.HasValue you know if it is actually set to something reasonable. You shouldn't depend on some "magic values" to decide if a value is initialized or not.

Stefan Steinegger