How to implement IDbContextFactory for use with Entity Framework data migrations

Entity FrameworkData Migration

Entity Framework Problem Overview


I am trying to use Entity Framework data migrations, as described in http://blogs.msdn.com/b/adonet/archive/2012/02/09/ef-4-3-code-based-migrations-walkthrough.aspx">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?

Entity Framework Solutions


Solution 1 - Entity Framework

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.

Solution 2 - Entity Framework

Like @Soren pointed out, instead of using IDbContextFactory, not supported on some earlier EF Core releases (i.e. EF Core 2.1), we can implement IDesignTimeDbContextFactory<TContext>, which supports the missing ConnectionString parameter.

For a settings.json based aproach, which you can use with either of the referred interfaces, check @Arayn's sample which allows us to define "ConnectionStrings:DefaultConnection" value path

Update 1

According to @PaulWaldman's comment, on EF Core 5 support for IDbContextFactory was reintroduced. For further details, check his comment below.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTim CoulterView Question on Stackoverflow
Solution 1 - Entity FrameworkdougajmcdonaldView Answer on Stackoverflow
Solution 2 - Entity FrameworkJulio NobreView Answer on Stackoverflow