2017-03-06 74 views
0

我正在研究本教程Getting Started with ASP.NET Core and Entity Framework Core using Visual Studio,我想從GitHub存儲庫將它部署到Azure。在Azure中使用「Web App + SQL」我可以成功部署一次,但是當我對數據庫進行更改並重新部署時,出現錯誤「應用現有遷移可能會解決此問題...」從存儲庫部署ASP.NET Core Web App + SQL

因此有什麼辦法可以在應用程序重新部署時使用新的遷移來觸發數據庫更新?

只是一個說明,我知道有直接從Visual Studio部署和管理這樣的應用程序的方法,但我想學習如何從存儲庫中完成它。

注:我發現這個similar question和我嘗試添加context.Database.Migrate()到Startup.cs的配置方法,下面DbInitializer.Initialize(context);,當我跑了它在我的機器上,這並不會造成問題,但是當我部署它,我得到了「500內部服務器錯誤:啓動應用程序時發生錯誤。「

回答

0

I tried adding context.Database.Migrate() to the Configure method of Startup.cs underneath DbInitializer.Initialize(context); and this didn't cause a problem when I ran it on my machine but when I deployed it I got "500 Internal Server Error: An error occurred while starting the application."

根據你的描述,我跟着你提到的tutorial來測試這個問題。我在這個section加入DbInitializer.cs下配置方法添加context.Database.Migrate()Startup.cs如下:

DbInitializer.Initialize(context); 
context.Database.Migrate(); 

我添加了一個名爲IdNo爲學生類的新屬性,然後啓動了Web應用程序,我可能會遇到以下錯誤:

enter image description here

注:如果Students表中沒有任何記錄,則DbInitializer.cs會增加飼料的記錄,那麼我恩反制上述錯誤。

這裏是關於DatabaseFacade.EnsureCreated()DatabaseFacade.Migrate()摘要:

DatabaseFacade.EnsureCreated()

Ensures that the database for the context exists. If it exists, no action is taken. If it does not exist then the database and all its schema are created. If the database exists, then no effort is made to ensure it is compatible with the model for this context. Note that this API does not use migrations to create the database. In addition,the database that is created cannot be later updated using migrations. If you are targeting a relational database and using migrations, you can use the DbContext.Database.Migrate() method to ensure the database is created and all migrations are applied.

DatabaseFacade.Migrate()根據您的情況

Applies any pending migrations for the context to the database. Will create the database if it does not already exist. Note that this API is mutually exclusive with DbContext.Database.EnsureCreated(). EnsureCreated does not use migrations to create the database and therefore the database that is created cannot be later updated using migrations.

,你需要利用遷移功能來更新你的數據庫模式。據我所知,EF Core不支持自動遷移,你可以按照類似的case和這個git issue。您可以在DbInitializer.cs中使用context.Database.Migrate()而不是context.Database.EnsureCreated(),並通過add-migration手動添加遷移文件,並將創建的遷移文件提交到您的GitHub存儲庫。

enter image description here

注:您需要照顧的種子數據的DbInitializer.cs,以避免在插入相同的記錄。

+0

是的!我只是將'context.Database.EnsureCreated()'改爲''DbInitializer.cs'中的'context.Database.Migrate()'以及手動添加遷移文件,並且它工作的很好。謝謝! –