![](/img/trans.png)
[英]Entity Framework code-first: migration fails with update-database, forces unneccessary(?) add-migration
[英]Entity Framework: Add-Migration fails with Unable to update database
我一直在項目中使用Entity Framework(5.0)一段時間(VS2012 Express中的ASP.NET MVC)。 但是,現在,我無法再添加遷移。
PM > Add-Migration -projectName MyProject.DAL TestMigration
Unable to update database to match the current model because there are pending changes and automatic migration is disabled. Either write the pending model changes to a code-based migration or enable automatic migration. Set DbMigrationsConfiguration.AutomaticMigrationsEnabled to true to enable automatic migration.
我不知道這是否提供任何線索,但“無法...”文本顯示為紅色。
我試圖啟用自動遷移(這是沒有意義的,因為我正在嘗試將掛起的模型更改寫入基於代碼的遷移)並導致數據庫中所需的遷移。 然而,這不是我想要的,因為我在項目中沒有遷移。
我試圖刪除數據庫並重新創建數據庫。 重新創建數據庫(直到上一次遷移),但是當我嘗試使用Add-Migration時,仍然會出現“無法更新..”錯誤。
編輯
我嘗試了-force參數,但沒有區別。
我的配置類的內容(我在上一次遷移后沒有改變任何內容):
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(Bekosense.DAL.Context.BekosenseContext context)
{
context.Database.ExecuteSqlCommand(Properties.Resources.TriggerAlertMessageDrop);
context.Database.ExecuteSqlCommand(Properties.Resources.TriggerAlertMessageCreate);
context.Database.ExecuteSqlCommand(Properties.Resources.TriggerAlertMessageSentDrop);
context.Database.ExecuteSqlCommand(Properties.Resources.TriggerAlertMessageSentCreate);
context.Database.ExecuteSqlCommand(Properties.Resources.AddDbUsers);
}
編輯2我發現當我在DbContext中評論以下行時,我能夠進行添加遷移:
//Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyContext, Configuration>());
當我將該行置於活動狀態並注釋掉配置文件中的所有內容時,它仍然無效。 為什么Database.SetInitializer行會導致這種奇怪的行為?
您可以重置實體框架以解決您的問題[ 但要記住它會將遷移帶到默認狀態 ]
注意:要在執行以下操作之前進行備份
您需要刪除當前狀態:
您將在數據庫中找到__MigrationHistory表[在App_Data文件夾下]
然后在程序包管理器控制台中運行以下命令:
Enable-Migrations -EnableAutomaticMigrations -Force
使用或不使用-EnableAutomaticMigrations
最后,你可以運行:
Add-Migration Initial
永遠不要使用automigrations,這在過去給我帶來了問題(當遷移數據庫時,使用正確的方法從頭開始!)
這一行應該在你的global.asax中:
Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyContext, Configuration>());
而不是你的DbContext!
如果以上內容無效,其他提示:
也許您的應用程序中有多個圖層:
Add-Migration 000 -StartupProjectName "NameOfTheProjectInSolutionExplorer" -ConfigurationTypeName "MyConfiguration" -ConnectionString "theconnectionstring;" -ConnectionProviderName "System.Data.SqlClient" -Verbose
以上是我用於多層應用程序的Add-Migration命令。
更新數據庫也是一樣的
Update-Database -ConfigurationTypeName "SlaveConfiguration" -StartupProjectName "FacturatieMVCv2.Data" -Verbose -script
在我的情況下,我有同樣的錯誤,因為我在遷移期間在構造函數方法上強制類DbContext上的ObjectContext.CommandTimeout。
嘗試刪除它
((IObjectContextAdapter)this).ObjectContext.CommandTimeout = 5000;
這對我有用:
update-database -targetmigration:"0" -force -verbose
add-migration Initial
update-database
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.