我想知道如何为生产数据库运行“更新数据库”命令。
'Update-Database' 数据库在我的本地机器上工作正常,但我如何让它适用于生产数据?
因此,如果我对我的应用程序进行更改,然后通过 Visual Studio 运行“发布”,这对于代码方面的工作正常,但我如何为生产数据运行“更新数据库”命令。
希望这个问题有意义...
谢谢,
我想知道如何为生产数据库运行“更新数据库”命令。
'Update-Database' 数据库在我的本地机器上工作正常,但我如何让它适用于生产数据?
因此,如果我对我的应用程序进行更改,然后通过 Visual Studio 运行“发布”,这对于代码方面的工作正常,但我如何为生产数据运行“更新数据库”命令。
希望这个问题有意义...
谢谢,
请参阅在生产中使用实体框架(代码优先)迁移,以便您的应用程序在实体框架初始化时自动更新数据库。
现在,如果您更愿意手动控制迁移,您可以在开发人员机器上使用 Update-Database 命令的 -Script 参数来生成 SQL 脚本,然后您可以针对生产数据库运行这些脚本。
http://msdn.microsoft.com/en-us/data/jj591621.aspx(请参阅获取 SQL 脚本部分)
补充@David已经说过的话......
就个人而言,我不相信automatic updates
“实时”场景,而且我总是更喜欢手动数据库管理(即,permissions
需要创建或更改 Db 存在问题 - 更不用说共享托管等) - 但从我所见在同步方面,迁移非常可靠(事实上,通常“解开”它们的唯一方法是删除 Db 并强制完全/全新更新)。
这是我不久前发表的一篇关于如何script
和synchronize database / code
面向部署场景(以及何时出现问题)的帖子。它不适用于您(还),但要记住一些事情。
您是否只想在应用程序运行的时间和地点(开发和生产)自动更新数据库到最新版本?
这可能不是一个好主意,除非在您知道可以信任自动迁移并且手动迁移数据库不可行的非常简单的场景中。请看这个答案:https ://stackoverflow.com/a/15718190/2279059 。如果您忽略此警告,请继续阅读。
Add the following to web.config
:
<entityFramework>
<contexts>
<context type="MyAssembly.MyContext, MyAssembly" disableDatabaseInitialization="false">
<databaseInitializer type="System.Data.Entity.MigrateDatabaseToLatestVersion`2[[MyAssembly.MyContext, MyAssembly], [MyAssembly.Migrations.Configuration, MyAssembly]], EntityFramework" />
</context>
</contexts>
This may look scary, but it does basically the same as the following code:
Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyContext, Migrations.Configuration>());
If you have no luck with web.config
, then you may also try to put this code into Global.asax
. I personally prefer configuration over code.
If you want your config file to look cleaner, you can also derive a new class from the template MigrateDatabaseToLatestVersion
class so you don't need to use the cryptic syntax for passing type arguments in your web.cofig
file:
public class MyDatabaseInitializer : public MigrateDatabaseToLatestVersion<MyContext, Migrations.Configuration> {}
What this does is to set a database initializer which automatically updates the database to the latest version.
(Source and more details: Entity Framework Code First Web.config Initialization)
Another solution that has worked for me was this: In my local web.config file, I set the connection string to point to the production server.
Then all the PM Console commands will be run on the production server. I can update-database
or revert migrations as needed, and the changes will apply to the production database.
You can run the Update-Database EF Tools command using the Production connection string as follows:
Update-Database -Args '--environment Production'
Source: https://docs.microsoft.com/en-us/ef/core/cli/powershell#aspnet-core-environment
As stated by others, you have to be extra careful, you should definitely try it first on a Staging environment.