I am trying to run migrations with custom DbContext.
var migrationConfiguration = new DbMigrationsConfiguration { AutomaticMigrationsEnabled = true };
migrationConfiguration.ContextType = typeof(DataContext);
var migrator = new DbMigrator(migrationConfiguration);
migrator.Update();
This throws Migration Exception, because DataContext
does not implement parameterless constructor:
The target context 'System.Data.Entity.DbContext' is not constructible. Add a default constructor or provide an implementation of IDbContextFactory.
The DataContext
constructor requires parameters, but I already have IDbContextFactory<DataContext>
created. How do I tell DbMigrator, to use existing implementation of IDbContextFactory<DataContext>
?
The IDbContextFactory<>
has be in same assembly and provide parameterless constructor.
Another way is to inherit DbConfiguration and set factory in parameterless constructor of derived class (I'm using MEF to get class derived from IDbContextFactory):
public class DataContextConfiguration : DbConfiguration
{
public DataContextConfiguration()
{
SetContextFactory(() => (DataContext)new CompositionManager().Container.GetExportedValue<IDataContextFactory>().Create());
}
}
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