Entity-framework – Entity Framework Code First: Enable-Migrations error

code-firstef-code-firstentity-frameworkentity-framework-migrations

This should be a pretty basic question regarding parameter use when running the Enable-Migrations command for the first time for Entity Framework Code First in the Package Manager Console. Here is how my solution is separated out:

  • I have a project called MyMvcApp.DomainEntities which contains my domain entity POCO classes and interfaces for their repositories.
  • I have a project called MyMvcApp.DataModeling which contains the EF reference (DbContext, repository implementations).
  • Lastly, I have a MyMvcApp.Web project which is the MVC4 project and also contains the EF connection string (to a local SQL Server DB) in the web.config.

When I run Enable-Migrations, I get a nasty error saying:

Could not load assembly 'MyMvcApp.DataModeling'. (If you are using Code First Migrations inside Visual Studio this can happen if the startUp project for your solution does not reference the project that contains your migrations. You can either change the startUp project for your solution or use the -StartUpProjectName parameter.)

I've run through seemingly every permutation of "Default Project Name" (the Package Manager Console drop down) and adding -ProjectName to no avail. (My solution's startup project is the MVC project FYI).

Given how I've separated my projects, how do I get the Enable-Migrations command to work?

Best Answer

It turns out the issue is that you absolutely need an App.config file with your connection string in the project with the DbContext class to enable migrations. In my case, this is the MyMvcApp.DataModeling project. I thought I could use the connection string in my MVC project's Web.config file by adding a -StartUpProjectName 'MyMvcApp.Web' parameter to my Enable-Migrations console command, but that doesn't seem to work.

For what it's worth, if you simply want to generate the database and not enable migrations, you don't need an App.config in your DataModeling project. You can just add the line of code below to your Global.asax file and run your app:

using (var context = new EntityContext())
{
    context.Database.Initialize(false);
}