未执行MigrateDatabaseToLatestVersion [英] MigrateDatabaseToLatestVersion not executed
问题描述
我不知道为什么我的最新迁移在应用程序启动时(或至少在首次访问数据库上下文时)没有自动执行.我曾经在开发过程中手动运行 update-database ,但是我想测试它是否会在托管的测试环境中自动升级.
I can't figure out why my latest migration is not getting executed automatically on application startup (or at least on first access of the database context). I used to run update-database manually in development, but I want to test whether it will upgrade automatically on my hosted test environment.
在Application_Start()中:
Database.SetInitializer<FepazoContext>(
new MigrateDatabaseToLatestVersion<FepazoContext, FepazoConfiguration>())
在FepazoConfiguration中:
internal sealed class FepazoConfiguration :
DbMigrationsConfiguration<Fepazo.Models.FepazoContext>
{
public FepazoConfiguration()
{
AutomaticMigrationsEnabled = true;
}
}
我什至将其添加到FepazoContext的构造函数中:
public FepazoContext() : base("DefaultConnection")
{
Database.Initialize(false);
}
一些额外的信息:
- 该迁移是通过 add-migration 自动创建的,看起来还不错.
- 查询
__MigrationHistory
表时,我看到迁移尚未按执行记录. - 我确认Web.config文件中未覆盖初始化程序或
AutomaticMigrationsEnabled
设置. -
FepazoContext
构造函数中的断点和FepazoConfiguration
受到打击.
- The migration was automatically created through add-migration and looks ok.
- When I query the
__MigrationHistory
table, I can see that the migration is not yet 'recorded' as executed. - I verified that the initializer or the
AutomaticMigrationsEnabled
setting isn't overridden in Web.config file. - Breakpoints in
FepazoContext
constructor and theFepazoConfiguration
are getting hit.
我忘记了什么吗?我可以更深入地找出问题出在哪里吗?
Am I forgetting something ? Can I dig deeper to find out where it goes wrong ?
更新
将True
传递给Database.Initialize
来尝试强制迁移也无效. Database.CompatibleWithModel(true)
返回false-因此系统会检测到差异,但是不会执行挂起的迁移!
Passing True
to Database.Initialize
to try and force the migration also has no effect. Database.CompatibleWithModel(true)
returns false - so the system detects there is a difference, however it does not execute the pending migration!
public FepazoContext() : base("DefaultConnection")
{
if (!Database.CompatibleWithModel(true))
{
// This is executed (each time the code enters)
Database.Initialize(true);
}
}
解决方法
作为一种解决方法,我在设置初始值设定项后立即显式调用DbMigrator.Update()
.尽管我仍然想知道为什么它不能自动运行,但确实可以解决问题.
As a workaround, I call DbMigrator.Update()
explicitly right after setting the initializer. That does the trick, although I'd still like to know why it doesn't work automatically...
protected void Application_Start()
{
// <...>
Database.SetInitializer<FepazoContext>(
new MigrateDatabaseToLatestVersion<FepazoContext, FepazoConfiguration>());
var dbMigrator = new DbMigrator(new FepazoConfiguration());
dbMigrator.Update();
// <...>
}
推荐答案
根据另一个在此处答案初始化程序要等到与数据库进行交互后才能运行.答案说明了如何强制初始化程序立即运行.
According to another answer on here the initializer doesn't run until there is some interaction with the database. The answer explains how to force the initializer to run immediately.
这篇关于未执行MigrateDatabaseToLatestVersion的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!