How can I set the schema dynamically for a Code First DbContext?

时间:2016-03-04 18:17:13

标签: ef-code-first entity-framework-6 database-schema

I have an EF6 Database First application that uses tables generated to an edmx from the dbo schema.

To update certain large pricing tables that work in concert with each other, I create new tables in a new schema based on the date, then inside a transaction, move the current tables to a backup schema, and move the new tables to the dbo schema. This is implemented using a new MetadataWorkspace created by reading the edmx file and changing the schema, and allows me to have two DbContexts where one works with the existing data in the dbo schema, and the other works with the new tables in the new schema. And works great for Database First! See this SO article.

For CodeFirst, one can set the modelBuilder.HasDefaultSchema in OnModelCreating, but then the DbContext is locked down, and OnModelCreating is not called again for new DbContext instances, so whatever schema was set is now used for all such DbContexts for the duration of the application.

My question is – how can I dynamically change the DbContext with CodeFirst where I can have two DbContext, each using different schema? I cannot just define two DbContext derived classes since the schema name is dynamic.

2 个答案:

答案 0 :(得分:0)

显然,除了DbContext被锁定并保留模式名称之外,这不可能完成。我计划通过保持第二个模式名称而不是动态来解决这个需求。如果可以"克隆"那将会很好锁定的DbContext有一个新的模式名称,但目前我无法找到。闭。

答案 1 :(得分:0)

您可以在EF6中动态设置架构。您需要调整初始化DBContext的方式。 我找到了我在这里寻找的大部分内容: Multi-Tenant With Code First EF6