简体   繁体   English

EF Change数据库上下文

[英]EF Change Database context

i am creating a sort of data importer and I have to work from different databases/tables, depending on the source database I'm importing. 我正在创建一种数据导入器,并且我必须根据要导入的源数据库在不同的数据库/表中工作。

So I started creating a Model with EF for every type of database I have to work with. 因此,我开始为要使用的每种类型的数据库创建带有EF的模型。

Based on the application setting, I have to import data from a particular database. 根据应用程序设置,我必须从特定数据库中导入数据。

So what I want to do is something like that: 所以我想做的是这样的:

var myDB; //the schema I need;
switch(DBType){
   case DBTypes.Application1:
          myDB = new APP1_Entities();
          break;
   case DBTypes.Application2:
          myDB = new APP1_Entities();
          break;
}

There is some way I can do this (or some kind of) with C# and EF? 有某种方法可以使用C#和EF做到这一点(或某种方式)? Thanks for everyone! 谢谢大家!

A good way to solve this would be through dependency injection. 解决此问题的一个好方法是通过依赖项注入。 This way the dependency is inverted and you are not "newing up" the context in the method. 这样,依赖关系就被反转了,您不必在方法中“更新”上下文。

public void DoSomething(DbContext context)
{
    myDb = context;

    //other logic here
}

This gives control of the method to the caller. 这将控制权交给调用者。 For more information there are plenty of resources all over the web. 有关更多信息,网络上有很多资源。 MSDN documentation is here: https://msdn.microsoft.com/en-us/library/hh323705(v=vs.100).aspx MSDN文档在这里: https : //msdn.microsoft.com/zh-cn/library/hh323705(v=vs.100).aspx

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

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