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

database-schema ef-code-first entity-framework-6


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.

5/23/2017 12:23:47 PM

Accepted Answer

Apparently this cannot be done but once since the DbContext is locked down and keeps the schema name. I plan to address this need by keeping the second schema name fixed rather than dynamic. Would be nice if could "clone" the locked down DbContext with a new schema name but currently not possible anyway that I have found. Closing.

3/18/2016 7:55:39 PM

Popular Answer

You can set the the schema dynamically in EF6. You need to adjust the way you initialize your DBContext though. I found most of what I was looking for here: Multi-Tenant With Code First EF6

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow