3 回答
TA贡献1801条经验 获得超8个赞
如果您的迁移无法正常进行,请尝试Database.Initialize(true)在DbContext ctor中进行设置。
public CustomContext(DbConnection connection)
: base(connection, true)
{
Database.Initialize(true);
}
我在迁移中也遇到类似的问题。在我的解决方案中,我必须始终在ctor中设置数据库初始化程序,如下所示
public CustomContext(DbConnection connection)
: base(connection, true)
{
Database.SetInitializer(new CustomInitializer());
Database.Initialize(true);
}
在自定义初始化程序中,您必须实现InitalizeDatabase(CustomContex context)方法,例如。
class CustomInitializer : IDatabaseInitializer<CustomContext>
{
public void InitializeDatabase(CustomContext context)
{
if (!context.Database.Exists || !context.Database.CompatibleWithModel(false))
{
var configuration = new Configuration();
var migrator = new DbMigrator(configuration);
migrator.Configuration.TargetDatabase = new DbConnectionInfo(context.Database.Connection.ConnectionString, "System.Data.SqlClient");
var migrations = migrator.GetPendingMigrations();
if (migrations.Any())
{
var scriptor = new MigratorScriptingDecorator(migrator);
string script = scriptor.ScriptUpdate(null, migrations.Last());
if (!String.IsNullOrEmpty(script))
{
context.Database.ExecuteSqlCommand(script);
}
}
}
}
}
添加回答
举报