Home > .Net > Entity Framework Error: OriginalValues cannot be used for entities in the Added state

Entity Framework Error: OriginalValues cannot be used for entities in the Added state

September 19th, 2013

When saving new entries to a SQL Server database using the Entity Framework, I came across the following exception error:

OriginalValues cannot be used for entities in the Added state

There may be a number of reasons why the exception was raised but I found that in my case I had to check the data I was trying to save to make sure that values were specified for all the fields and that the fields were in the ranges required by the SQL Server database.

Here is a list of the checks I had to implement before writing the data to the database using Entity Framework:-

1. Check that a value required in the SQL database didn’t have a null value, e.g. make sure a string field had an empty value “” rather than null.

2. Check that string values weren’t too long to fit, e.g. check that if the database field had a max length of 40 characters I wasn’t trying to save more characters than would fit.

3. Check that any DateTime fields were not out of range for the SQL DateTime fields. .Net DateTime defaults have the value 1/1/1 but SQL dates have a different range to .Net and cannot accept values of 1/1/1.

For each DateTime field I called this function to check (and force) the fields into a range the SQL database would accept.

public static DateTime Default(DateTime Value)
{
   if (Value == null)
   {
      return DateTime.Today;
   }
   else
   {
      // Check the .Net value is in a valid range for a SQL DateTime.
      if (Value < SqlDateTime.MinValue.Value || Value > SqlDateTime.MaxValue.Value)
      {
         Value = DateTime.Today;
      }
      return Value;
   }
}

  1. No comments yet.
  1. No trackbacks yet.