Migrations and contexts with parameterized constructors
When using migrations we need to have public parameterless constructors or implement a factory.
Problem
If your context takes parameters in all of its public constructors, then it cannot be used by migrations, since the migrations framework does not know how to instantiate it. The error will be something like "unable to find the DbContext
", which is far from helpful.
How to solve it…
The solution for this is to have a public context factory class in the same assembly as your migrations assembly. This context factory needs to implement IDbContextFactory<TContext>
and return a context instance from its Create
method:
public class MyContextFactory : IDbContextFactory<MyContext> { public MyContext Create(DbContextFactoryOptions options) { //return a MyContext instance with its parameters return new MyContext("<SomeConnectionString>"); } }
For similar reasons, this class...