EF 4.3在一个数据库中使用多个DbContexts进行自动迁移 [英] EF 4.3 Auto-Migrations with multiple DbContexts in one database

查看:181
本文介绍了EF 4.3在一个数据库中使用多个DbContexts进行自动迁移的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用具有多个代码优先的DbContexts的EF 4.3迁移。我的应用程序分成几个插件,可能有自己的DbContext关于他们的域。该应用程序应该使用一个单一的sql数据库。



当我尝试在空数据库中自动迁移上下文时,这只能在第一个上下文中成功。每个其他上下文都需要将AutomaticMigrationDataLossAllowed-Property设置为true,然后尝试删除之前的表。



所以我的问题是:




  • 我如何告诉迁移配置

  • 在单个数据库中使用自动迁移处理多个DbContexts的正确工作流程是什么?



谢谢!

解决方案

我们可以想到两种可能的解决方案:


  1. 创建包含每个上下文的所有实体的聚合上下文,并从迁移配置类引用此超级上下文。这样,所有的表都将在用户的数据库中创建,但是数据只会在他们已经安装了插件的数据库中。


  2. 使用单独的数据库对于每个上下文如果您在上下文之间共享实体,请添加自定义迁移,并将 CreateTable(...)调用替换为 Sql(CREATE VIEW)。 ..)调用从实体的始发数据库获取数据。


我会尝试#1,因为它将所有内容都保存在一个数据库中。您可以在解决方案中创建一个独立的项目,以包含迁移和超级上下文。只需添加项目,引用所有插件的项目,创建一个包含所有实体的上下文,然后在此新项目中调用Enable-Migrations。事情应该如预期那样工作。


I'm trying to use EF 4.3 migrations with multiple code-first DbContexts. My application is separated into several plugins, which possibly have their own DbContext regarding their domain. The application should use one single sql-database.

When I try to auto migrate the contexts in an empty database, this is only successful for the first context. Every other context needs the AutomaticMigrationDataLossAllowed-Property set to true but then tries to drop the tables of the previous one.

So my question is:

  • How can I tell the migration-configuration just to look after the tables defined in their corresponding context and leave all others alone?
  • What is the right workflow to deal with multiple DbContexts with auto-migration in a single database?

Thank you!

解决方案

Code First Migrations assumes that there is only one migrations configuration per database (and one context per configuration).

I can think of two possible solutions:

  1. Create an aggregate context that includes all the entities of each context and reference this "super" context from your migrations configuration class. This way all the tables will be created in the user's database, but data will only be in the ones that they've installed plugins for.

  2. Use separate databases for each context. If you have shared entities between the contexts, add a custom migration and replace the CreateTable(...) call with a Sql("CREATE VIEW ...") call to get the data from the entity's "originating" database.

I would try #1 since it keeps everything in a single database. You could create a seperate project in your solution to contain your migrations and this "super" context. Just add the project, reference all of your plugins' projects, create a context that includes all of the entities, then call Enable-Migrations on this new project. Things should work as expected after that.

这篇关于EF 4.3在一个数据库中使用多个DbContexts进行自动迁移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆