Wednesday, May 16, 2012

Sql datetime data type and EF4: The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.


Solution to this problem depends on the complexity of the object you are trying to save. The main reason for this error is "out of range value in the datetime field".

For more detail please check the link mentioned below.


Lots of information is available on the internet about this problem but most of them holds true if we are dealing with simple object.

I got the same error message but cause was different. My table has multiple foreign keys and as a result the object I was trying to save has lots of datetime column (CreateDate and ModifiedDate of each foreign keys table).

I tried different ways to solve this issue.

1. I checked the object to make sure all the datetime column has valid datetime value.I added the dates in all the columns (nullable columns) in the tables just to test.

   Result: - Still got the same error.
   Conclusion: - There is something else which prevent this save process. 

2. After lots of research I found that I was using the values of foreign keys tables which was retrieved from the other instance of dataContext object. Catch is, if multiple foreign key tables are involved then get there values from same instance of dataContext object and pass it to your object and then save it. 
   Result: -object got saved.                          

  public int SaveEMail (EMail objEMail)
        {        
          ImportRepository _repImport = new ImportRepository();                         
          using (Model1Container ctxt = this.CreateContext())
            { 
                EMail eEMail = new EMail(); 
                eEMail.Name = objEMail.Name;
                eEMail.TechnicalEmail= objEMail.TechnicalEmail;
                eEMail.BusinessEmail= objEMail.BusinessEmail;
                eEMail.CreateDate = DateTime.Now;
                eEMail.Import = _repImport.GetImport(ctxt, objEMail.Import.ID);   // get the values of foreign keys table           

                ctxt.AddToEMails(eEMail); 
                ctxt.SaveChanges();
                return eEMail.ID;

            }
     }                       

   I am not sure why it is not working in step one but this solution works.