在实体框架运行时更改数据库,无需更换连接 [英] Change Database during runtime in Entity Framework, without changing the Connection

查看:276
本文介绍了在实体框架运行时更改数据库,无需更换连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有承载50个数据库具有相同的架构服务器,我要开始在我们的下一个版本使用实体框架。

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

我并不需要为每个这些数据库的一个新的连接。一个连接的权限可以跟所有的50个数据库,以及用于数据管理和速度(这是一个应用程序的WebAPI)我不想每次我跟每个数据库,如果我时间来实例化一个新的EF上下文确实有不,当然,除非,如果发生这种情况每一个请求到服务器的话没有什么大不了的时间。

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.

我真正需要的是改变使用[数据库名称]命令的能力,我假设最终被发送到从EF服务器。

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

有没有办法在code做到这一点? EF是否保持一个读/在这指的是可以在飞行的SaveChanges调用()等之前可以更改数据库名称的上下文写属性??

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.??

感谢您!

鲍勃

推荐答案

您可以看看:


  • SO关于通过现有的SQL连接到问题
    的EntityFramework上下文

  • 和<一个href=\"https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.changedatabase(v=vs.110).aspx?f=255&MSPPError=-2147217396&cs-save-lang=1&cs-lang=csharp#$c$c-snippet-1\"相对=nofollow>这篇文章描述如何
    现有的连接更改数据库。

请让我知道是否需要任何额外的帮助。

Please let me know if any additional help is needed.

编辑结果
更新2次链接,点<一个href=\"https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.changedatabase(v=vs.110).aspx?f=255&MSPPError=-2147217396&cs-save-lang=1&cs-lang=csharp#$c$c-snippet-1\"相对=nofollow> SqlConnection.ChangeDatabase 方法。结果
所以最终code将同样着眼于以下内容:

Edited
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)
  {
    Console.WriteLine(product.ProductName);
  }

  // switch database
  sqlConnection.ChangeDatabase("Northwind");
  Console.WriteLine("Database: {0}", connection.Database);
}

这篇关于在实体框架运行时更改数据库,无需更换连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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