Entity Framework 5 Codefirst and C# – context commit doesn’t show in the database

For those of you who are using Entity Framework codefirst and are experiencing the perplexing issue where all of the code runs without any exceptions and your context’s Commit() is called, but you look in your database and don’t see any changes or the results you’re looking for, think back if there have been any manual updates to the database. If you update a table manually and outside of “Add-Migration” and “Update-Database” then it can mess up the context and prevent any data changes.

The solution was to remove the relevant migrations for that table from the Migrations folder AND from __MigrationHistory table, remove the table from the DB and then rerun “Add-Migration” / “Update-Migration” combo. What I didn’t try, but may have worked is making some change to that table’s model running “Add-Migration” / “Upgrade-Migration” again after the manual change to the table. I was at a stage where it was a brand new table, but if you already have data in the table my solution won’t work for you. Try the second method and let me know.

A second reason for code running fine without exceptions, but no data showing is if the data being sent is “out of range” or a similar data issue. Here’s an error I received recently, “The conversion of a nvarchar data type to a datetime data type resulted in an out-of-range value.” A date value as a string was all zeros and the SQL Server 2008 R2 database did not like that and rejected the entire record, so nothing showed. The solution was to put more strict checks on the data being sent to see if it was out of bounds.

For valid SQL DateTime values I use this:

Code Snippet
  1. private DateTime getValidSqlDate(DateTime date)
  2. {
  3.     if (date < (DateTime)SqlDateTime.MinValue)
  4.     {
  5.         return (DateTime)SqlDateTime.MinValue;
  6.     }
  7.     else if (date > (DateTime)SqlDateTime.MaxValue)
  8.     {
  9.         return (DateTime)SqlDateTime.MaxValue;
  10.     }
  11.     else
  12.     {
  13.         return date;
  14.     }
  15. }
Posted in api, asp.net, coding

Leave a Reply

Your email address will not be published. Required fields are marked *

*