Thursday, August 21, 2014

Entity Framework 6 Migration: Could not load file or assembly

If this error finds you while doing EntityFramework migration my experience may help.

I have a solution like this:

   -   Example.Data
   -   Example.Web

The DbContext resides in my Example.Data project and the Example.Web is the startup project that feeds the connection string. Example.Web has a reference of Example.Data.

The thing that actually triggers the error is that I override the Seed method to seed some Roles and Users for my application. I also used custom Membership and Role provider configured with Web.config.

So when I run Update-Database command it fails with:
Could not load file or assembly Example.Web, Version=, Culture=neutral' or one of its dependencies.
The system cannot find the file specified.

Here is what I have in the seed method:

protected override void Seed(MyDbContext context)
    if (!Roles.RoleExists("Admin")) Roles.CreateRole("Admin");

This code needs the Role provider. But the provider classes are placed in Example.Web project. So when the migration take places the Example.Web assemble is not present in the output folder of Example.Data. That causes the file not found exception. If I manually copy the assemblies of Example.Web to Example.Data's output folder, it solves the problem.

The real fix for this problem however is to use AppDomainBaseDirectory switch with Update-Database command and provide the full path of the bin directory of Example.Web like:

Update-Database -Verbose -Force -AppDomainBaseDirectory "C:\Path\To\bin"

As the Example.Web has a reference to Example.Data, all the required assemblies will be in Example.Web's output folder.

By the way, the problem appeared after I migrated from EF5 to EF6.1. Somehow EF5 did the right thing for me so far.


Post a Comment