ros*_*lav 5 c# entity-framework ef-migrations
我正在尝试使用自定义DbContext运行迁移.
var migrationConfiguration = new DbMigrationsConfiguration { AutomaticMigrationsEnabled = true };
migrationConfiguration.ContextType = typeof(DataContext);
var migrator = new DbMigrator(migrationConfiguration);
migrator.Update();
Run Code Online (Sandbox Code Playgroud)
这会引发Migration Exception,因为DataContext它没有实现无参数构造函数:
目标上下文'System.Data.Entity.DbContext'不可构造.添加默认构造函数或提供IDbContextFactory的实现.
该DataContext构造函数需要参数,但我已经IDbContextFactory<DataContext>建立.我如何告诉DbMigrator,使用现有的实现IDbContextFactory<DataContext>?
它们IDbContextFactory<>位于同一程序集中并提供无参数构造函数。
另一种方法是继承 DbConfiguration 并在派生类的无参数构造函数中设置工厂(我使用 MEF 获取从 IDbContextFactory 派生的类):
public class DataContextConfiguration : DbConfiguration
{
public DataContextConfiguration()
{
SetContextFactory(() => (DataContext)new CompositionManager().Container.GetExportedValue<IDataContextFactory>().Create());
}
}
Run Code Online (Sandbox Code Playgroud)