How to implement IDbContextFactory for use with Entity Framework data migrations
Solution 1:
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:
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.