使用 EF4 Code First:如何在不丢失数据的情况下更改模型
在我的 Global.asax 中,我有以下行:
Database.SetInitializer<myDbSupport>
(new DropCreateDatabaseIfModelChanges<myDbSupport>());
如果没有这一行,那么当我更改模型时,sdf 数据库将不会具有正确的结构。这在开发环境中是可以的,但是当我转移到生产环境并想要更新数据库结构时,我当然不能删除表并丢失数据。
是否可以编写数据库更改脚本,并在使用更改后的结构部署模型之前运行此更新?
In my Global.asax I have the following line:
Database.SetInitializer<myDbSupport>
(new DropCreateDatabaseIfModelChanges<myDbSupport>());
If I don't have this, then when i change the model, the sdf database will not have the correct structure. This is ok in a dev environment, but when I move to production and want a DB structure update, i of course, can't afford to drop the table, and lose the data.
Is it possible to script DB changes, and run this update before deploying the model with the changed structure?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
初始化器用于开发。我认为任何直接从应用程序更改生产数据库的自动过程都是邪恶的。其他人可能会忘记它的存在,重新部署单个 .dll,然后您的数据库就会消失。
数据库升级是在应用程序维护期间而不是在首次请求新版本期间应作为升级脚本、安装包或手动升级的一部分单独执行的操作。 我昨天描述了迁移。
您正在寻找的是自定义初始化程序,它将执行在我的链接答案中创建的外部脚本。如果您包含许多额外的检查,这将避免运行脚本两次,这可能会部分起作用。但为什么?一旦你有了脚本,你就可以在完成后简单地执行它。
Initializer is for development. I consider any automatic process changing your production database directly from application as evil. Somebody else can simply forget the existence of it, redeploy single .dll and your database is gone.
Database upgrade is operation which should be executed separately as part of upgrade script, installation package or manual upgrade during application maintenance and not during first request to the new version. I described migration yesterday.
What you are looking for is custom intializer which would execute external script created in my linked answer. That can be partially working if you include a lot of additional checks which will avoid running script twice. But why? Once you have a script you can simply execute it once an you are done.