1

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.

Community
  • 1
  • 1
Dave
  • 1,822
  • 2
  • 27
  • 36

2 Answers2

0

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.

Dave
  • 1,822
  • 2
  • 27
  • 36
0

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

Community
  • 1
  • 1
EstebanSmits
  • 91
  • 2
  • 8
  • 1
    Thx but that can only be done once and then locks the DbContext and OnModelCreating is not called on new instances with different schema names. – Dave Mar 24 '16 at 01:26