So your Migration History Table is EF6, but the project is using EF505/23/2014
We had a little hiccup this morning with a project in development. We recently updated Edge to Entity Framework 6 (EF6). Projects are a constant flow around here, and as developers, we like to give our clients the latest and greatest. This particular project had been spun up right before our big in-house Edge update. It was a really important update as it offered a new system that supports plugins. There was an attempt to upgrade the new project to EF6 along with the new Edge updates. Everything went smoothly, minus upgrading EF.
It turns out, the __MigrationHistory table was updated to reflect EF6. The column ContextKey was added. ContextKey is a new addition in EF6. Unfortunately, the project was unable to be upgraded to EF6 and thus stayed at EF5.
Fast forward to this morning, I was tasked to add some new features to this project in development. In a Code First project, I typically add all of my database additions first to prevent any sort of interruption with the DataContext.
System.Data.SqlClient.SqlException (0x80131904): Cannot insert the value NULL into column 'ContextKey', table 'XXXXXX.dbo.__MigrationHistory'; column does not allow nulls. INSERT fails.
Lo and behind, the above error shows its ugly face. Ugh, what is this? I have never seen it before. Some quick Googling revealed nothing except mentioned EF6. I checked the project version and sure enough it was EF5. Odd. At this point, I have Justin over my shoulder trying to help me figure this out. He has the most experience on this particular project. Justin had also never seen the error. Time to investigate!
We ended up viewing the script output from the Update-Database command to find that the CREATE statement for the __MigrationHistory table did not include the column ContextKey and nor did the INSERT. This was obviously the problem. We needed to recreate the table.
I went into the database and deleted __MigrationHistory and commented out all of my changes I was attempting to make before the error. I proceeded to update the context again, and of course, it tried to re-create all of the tables. I opened up the script with:
Update-Database –Verbose –Script
and removed everything except for the __MigrationHistory table creation and entry. Voilà! That did just the trick. This put a record into the __MigrationHistory table that denoted the creation of the tables which already existed. I promptly uncommented my changes and updated again. Success!!!
Long story short, if your __MigrationHistory is getting ahead of itself and trying to be EF6:
- Delete dbo.__ MigrationHistory table
- Comment out your changes if you made any before you got the error (ones that didn’t make it to the database previously)
- Run Update-Database -Verbose –Script
- Remove all SQL statements EXCEPT the ones for dbo.__MigrationHistory
- Execute script
- Now you are free to update your context normally!