5

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 DataContextdoes 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 DataContextconstructor requires parameters, but I already have IDbContextFactory<DataContext> created. How do I tell DbMigrator, to use existing implementation of IDbContextFactory<DataContext>?

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
roslav
  • 470
  • 3
  • 15
  • Something else is wrong here - note the `System.Data.Entity.DbContext` (not `DataContext`) in the exception message. – Ivan Stoev May 27 '16 at 12:52
  • Show your context. http://stackoverflow.com/questions/11395283/how-to-implement-idbcontextfactory-for-use-with-entity-framework-data-migrations – Steve Greene May 27 '16 at 15:10

1 Answers1

4

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());
    }
}
roslav
  • 470
  • 3
  • 15