How to implement IDbContextFactory for use with Entity Framework data migrations

Tim Coulter picture Tim Coulter · Jul 9, 2012 · Viewed 26.2k times · Source

I am trying to use Entity Framework data migrations, as described in this post.

However, when I try to execute the Enable-Migrations step, I receive the following error in Package Manager Console:

The target context 'MyDataContext' is not constructible. Add a default constructor or provide an implementation of IDbContextFactory

So, I created a factory class that implements IDbContextFactory in the project that contains my DbContext class, but data migrations doesn't appear to recognize it.

Is there something that I should explicitly do to instruct data migrations to use this factory class?

Answer

dougajmcdonald picture dougajmcdonald · Jul 31, 2012

I also hit this problem as i wrote my context to take a connection string name (and then used ninject to provide it).

The process you've gone through seems correct, here is a snippet of my class implementation if it's of any help:

public class MigrationsContextFactory : IDbContextFactory<MyContext>
{
    public MyContext Create()
    {
        return new MyDBContext("connectionStringName");
    }
}

That should be all you need.