2017-03-06 88 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()'以及手动添加迁移文件,并且它工作的很好。谢谢! –