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应用程序,我可能会遇到以下错误:

注:如果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存储库。

注:您需要照顾的种子数据的DbInitializer.cs
,以避免在插入相同的记录。
是的!我只是将'context.Database.EnsureCreated()'改为''DbInitializer.cs'中的'context.Database.Migrate()'以及手动添加迁移文件,并且它工作的很好。谢谢! –