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()'以及手動添加遷移文件,並且它工作的很好。謝謝! –