Change Database during runtime in Entity Framework, without changing the Connection c# entity-framework sql-server


I have a server that hosts 50 databases with identical schemas, and I want to start using Entity Framework in our next version.

I don't need a new connection for each of those databases. The privileges of the one connection can talk to all of the 50 databases, and for data management and speed (this is a WebAPI application) I don't want to instantiate a new EF context every time I talk to each of the databases if I don't have to, unless of course if this occurs each time a request comes to the server then no big deal.

All I really need is the ability to change the USE [databasename] command, which I assume eventually gets sent to the server from EF.

Is there a way to accomplish this in code? Does EF maintain a read/write property in the Context that refers to the database name that could be changed on the fly before calling SaveChanges(), etc.??

Thank you!!!


9/17/2013 4:09:29 AM

Accepted Answer

You can take a look at:

  • SO question about passing existing SQL Connection to EntityFramework Context
  • and at this article describing how to change database on existing connection.

Please let me know if any additional help is needed.

Updated 2nd link to point to SqlConnection.ChangeDatabase method.
So eventually code would look similarly to the following:

MetadataWorkspace workspace = new MetadataWorkspace(
  new string[] { "res://*/" }, 
  new Assembly[] { Assembly.GetExecutingAssembly() });

using (SqlConnection sqlConnection = new SqlConnection(connectionString))
using (EntityConnection entityConnection = new EntityConnection(workspace, sqlConnection))
using (NorthwindEntities context = new NorthwindEntities(entityConnection))
  // do whatever on default database
  foreach (var product in context.Products)

  // switch database
  Console.WriteLine("Database: {0}", connection.Database);
5/23/2017 10:31:22 AM

Popular Answer

Don't Work hard, work smart !!!!

MYContext localhostContext = new MYContext();
MYContext LiveContext = new MYContext();
//If your databases in different servers
LiveContext.Database.Connection.ConnectionString = LiveContext.Database.Connection.ConnectionString.Replace("localhost", "Live");
//If your databases have different Names
LiveContext.Database.Connection.ConnectionString = LiveContext.Database.Connection.ConnectionString.Replace("DBName-Localhost", "DBName-Live");

the structure for databases should be the same ;)

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