单个Entity Framework MVC应用程序中的多个数据库? [英] Multiple databases in single Entity Framework MVC application?

查看:63
本文介绍了单个Entity Framework MVC应用程序中的多个数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Entity Framework在多个数据库之间切换。

数据库的名称将出现在下拉列表中,并选择我需要连接到该特定数据库的下拉列表项使用实体框架。

什么是最佳解决方案? EF是否提供了实现此目的的任何配置?如何配置应用程序?

How can I switch between multiple databases using Entity Framework.
The name of the databases will be coming in a drop down list and on selecting the dropdown list item I need to connect to that particular database using Entity Framework.
What is the best solution? Do EF provide any configuration for achieving this? How should the application be configured?

推荐答案

当您使用实体框架时,数据上下文类派生自 ObjectContext 自动在 DataModel.Desiner.cs 文件中创建。这个数据上下文类有3个构造函数,你应该使用第二个,它有连接字符串作为参数。



所以当用户更改数据库时,你应根据用户选择动态构建连接字符串(在最简单的情况下,如果所有数据库都在同一服务器上,则只应更改数据库的名称,因此您可以使用基于默认值的静态文本并仅替换通过使用 string.Format 来获取数据库名称的参数然后缓存此连接字符串(对于整个用户会话上下文)并将其用于您的数据访问代码,如下一个示例所示:

When you use entity framework an "data context" class, derived from ObjectContext is automatically created in the DataModel.Desiner.cs file. This "data context" class has 3 constructors and you should use the 2nd one, that has as parameter the connection string.

So when the user change the database, you should build dynamically the connection string based on the user selection (in the most simple situation if all databases are on the same server only the name of the database should change, so you could use a static text based on the default one and replace only the param for database name by using string.Format) then cache this connection string (for the entire user session context) and use it into your data access code like in the next example:
using (MyDataContextClasss dataContext= new MyDataContextClasss (connectionString))
{
      //You code for accessing the data by using EF!
}


这篇关于单个Entity Framework MVC应用程序中的多个数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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