EntityFramework – SQLException during database migration

Recently I’ve been doing some small refactoring of my pet project. Nothing too fancy – just namespace adjustment, variables and class renaming etc. However it turned out that even these minor changes can in fact be major ones. All of the sudden most of my integration tests started failing due to SQLException.
Exception
I am using Code First approach so I didn’t take me too much time to realize that for some reasons EntityFramework wanted to create already existing tables. I started looking into the way EF keeps track of the changes in the model and it turned out that it creates special table called

ContextKey
One of the most important columns in there is column called ContextKey, which identifies the class which describes migration policy. In my case this class originally looked that way

In that case value of the ContextKey column matches the full name of the class

The class after refactoring was slightly changed and now it looks that way

It is easy to overlook the change but now, full name of the class is

so EF loses the information about the migration and tries to migrate once again from the scratch. Fortunately there is an easy fix for that which doesn’t require dropping the database. All you have to do is to write simple update statement which set the proper ContextKey value.

Source code for this post can be found here

EntityFramework – SQLException during database migration

Fixing empty SQL server list in “Entity Data Model Wizard”

I consider myself as a quite experienced user of Nhibernate, that is why I decided to check what is going on on the other side of barricade and started playing with Entity Framework. I followed the steps of some tutorial and I stuck at the very beginning of it. I was about to generate model classes using “Entity Data Model Wizard” but it turned out that the wizard could not find my SQL server (despite the fact that server itself was up and running).
empty SQL server list
I remember having similar issue a while back, but at that time I wasn’t able to solve it (I ended up creating connections string manually). This time I wanted to give this issue a closer look. After a bit of digging I found the problem – the SQL server wasn’t broadcasting information about itself. In order to fix it and make the server visible to other computers and applications it is necessary to start SQL Server Browser service. To do that go to Start -> Run and type Services.msc
runservices
Then in newly opened window find SQL Server Browser service
SqlServerBrowser
Double click it and set up startup type to Automatic. You can also click Start button to make sure that service starts immediately
automaticserverbrowser
From now on SQL servers should be visible in “Entity Data Model Wizard”
filledserverlist

Fixing empty SQL server list in “Entity Data Model Wizard”