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?
Step 1 − Before running the application you need to enable migration. Step 2 − Open Package Manager Console from Tools → NuGet Package Manger → Package Manger Console. Step 3 − Migration is already enabled, now add migration in your application by executing the following command.
One way to create multiple migration sets is to use one DbContext type per provider. Specify the context type when adding new migrations. You don't need to specify the output directory for subsequent migrations since they are created as siblings to the last one.
IDbContextFactory<TContext> InterfaceA factory for creating derived DbContext instances. Implement this interface to enable design-time services for context types that do not have a public default constructor.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With