[英]Switching DB Context in LINQ Entity Framework asp.net MVC 5
In laravel they have eloquent that can change between databases.在 Laravel 中,它们具有可以在数据库之间变化的雄辩能力。
For example:例如:
$db = (statement) ? "mysql1" : "mysql2" ;
$users = DB::connection($db)
->select(...);
How do you do you do this in LINQ?你如何在 LINQ 中做到这一点?
Model data = (from table in context_db <--- how to i dynamically change this??
.Model
where table.ref_no == ref_no
select new Model
{
...
});
my web.config contextdb我的 web.config 上下文数据库
<add name="DBContext1" connectionString=" ... / >
<add name="DBContext2" connectionString=" ... / >
You should register your another DbContext in services, in ConfigureServices
method in Startup.cs and pass it to your constructor of your class like:您应该在服务中注册另一个 DbContext,在Startup.cs 的
ConfigureServices
方法中,并将其传递给类的构造函数,例如:
Startup.cs启动文件
services.AddDbContext<YourDbContextA>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("YourConnectionString")));
YourClass.cs (or YourClass.cshtml.cs) YourClass.cs(或 YourClass.cshtml.cs)
public class YourClass
{
private readonly YourDbContext _context;
public CreateModel(YourDbContext context)
{
_context = context;
}
}
You can register multiple DbContext
objects in services and can pass multiple DbContext
objects to your constructor
.您可以在服务中注册多个
DbContext
对象,并且可以将多个DbContext
对象传递给您的constructor
。
Later you can switch between your dbContextes:稍后您可以在 dbContextes 之间切换:
private DbContext getDbContext(bool statement)
{
if(statement)
return _dbcontext1;
else if(statement2)
return _dbcontext2;
else
return _someOtherDbContext;
}
private void foo()
{
Model data = (from table in getDbContext(statement)
where table.ref_no == ref_no
select new Model
{
...
});
}
You can do it by editing your ContextDB constructor.您可以通过编辑 ContextDB 构造函数来实现。
first you have to set a connection string on your web.config首先你必须在你的 web.config 上设置一个连接字符串
<add name="DBContext1" connectionString=" ... / >
<add name="DBContext2" connectionString=" ... / >
second on your contextdb constructor add a parameter for your connection.第二个在您的 contextdb 构造函数上为您的连接添加一个参数。
public partial class YourContextDB: DbContext
{
public YourContextDB(string connection = "name=DBContext1")
: base(connection )
{
}
... //basically ur models below
}
3rd you can now do this.第三,您现在可以执行此操作。
string connection = (statement) ? "name=DBContext2" : "name=DBContext1";
YourContextDB dbcontext = new YourContextDB(connection); //default is "name=DBContext1"
Model data = (from table in dbcontext <--- dynamic dbcontext
.Model
where table.ref_no == ref_no
select new Model
{
...
});
NOTE: you cannot use code-first Update-Database
with this solution.注意:您不能在此解决方案中使用代码优先
Update-Database
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.