简体   繁体   English

与多个数据库一起使用实体框架

[英]Working with Entity framework with multiple databases

I am very new to Entity Framework. 我是实体框架的新手。 I need to do something like below; 我需要做下面的事情;

When page loads it will display data from table1 in database1 depending on the data select from the first page it has to connect to different databases (These databases has same names. But can have slight changes). 页面加载时,它将根据从第一页选择的数据来显示来自database1中 table1的数据,它必须连接到不同的数据库(这些数据库具有相同的名称。但是可能会有一些变化)。 I already have a way get the connections to those different DBs. 我已经有一种方法可以连接到这些不同的DB。

I have no idea where should I start. 我不知道我应该从哪里开始。 Please guide me. 请指导我。 It is good if you can provide me with basic level information and examples. 如果您可以向我提供基本级别的信息和示例,那就太好了。

You would need to create a separate instance of database context for each database and specify connection string as a constructor parameter 您将需要为每个数据库创建数据库上下文的单独实例,并将连接字符串指定为构造函数参数

var dbContext = new MyDbContext("<connection string>")

if there is fixed list of connection strings then they can be stored in config file and used by name like 如果有固定的连接字符串列表,则可以将它们存储在配置文件中并按名称使用,例如

var dbContext = new MyDbContext("Name=FirstDb")

You can supply the Connection String to the DbContext constructor: 您可以将连接字符串提供给DbContext构造函数:

var db1 = new MyContext(connectionString1);
var db2 = new MyContext(connectionString2);

and in the context: 在上下文中:

public class MyContext : DbContext
{
    public MyContext(string cs) : base(cs) { }
}

you will need 2 models or context if you not using entity model. 如果不使用实体模型,则需要2个模型或上下文。 if your about to use the entity model then the wizard will ask for connection string, and you will create 2 model with 2 connection strings. 如果您要使用实体模型,则向导将询问连接字符串,然后您将使用2个连接字符串创建2个模型。

i prefer the model because it easy and you the changes in the database will handle your code in one update click 我更喜欢该模型,因为它很容易,并且您在数据库中所做的更改将在一次更新单击中处理您的代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM