Problem : OriginalValues cannot be used for entities in the Added state
I was working on a repository and came across an interesting, cryptic error that resulted from a fairly simple operation: Saving the changes.
Without getting into code details (which are irrelevant to the point), the call to the following statement failed:
Context.SaveChanges();
The error message read: OriginalValues cannot be used for entities in the Added state
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.
Comments
Post a Comment