在运行时更改的DbContext [英] Changing dbContext at runtime
问题描述
我有一个UsersContext:的DbContext用DbSet用户{搞定;组; }
I have a UsersContext : DbContext with a DbSet Users { get; set; }
UsersController.cs
public class UsersController : Controller
{
private UsersContext db = new UsersContext("dbA");
public ViewResult Index()
{
if (...)
db = new UsersContext("dbA");
else
db = new UsersContext("dbB");
return View(db.Users.ToList());
}
}
这将返回良好的关联列表。
如果让我选择我的DBB有好名单,但是当我去详细讨论的结果之一:
This returns the good associated list.
If I choose dbB I have the good list but when I go on detail on one of the results in :
public ViewResult Details(int id)
{
User user = db.Users.Find(id);
return View(user);
}
的分贝的的connectionString关联到DBA不是DBB。
为什么新的数据库没有很好initilized并保存?
The db's connectionString is associated to the dbA not the dbB. Why the new db is not well initilized and saved ?
推荐答案
这是因为你的首页
动作和详细信息
行动并不在同一个控制器实例执行。你可以把数据库名在会话变量并用它来创建的DbContext
实例。
That is because your Index
action and Details
action do not execute on the same controller instance. You can keep the database name in a session variable and use that to create the DbContext
instance.
public class UsersController : Controller
{
private UsersContext db;
protected override void Initialize(RequestContext requestContext)
{
base.Initialize(requestContext);
if (Session["Database"] == null)
db = new UsersContext("dbA");
else
db = new UsersContext((string)Session["Database"]);
}
public ViewResult Index()
{
if (...) {
db = new UsersContext("dbA");
Session
else
{
db = new UsersContext("dbB");
Session["Database"] = "dbB";
}
return View(db.Users.ToList());
}
}
这篇关于在运行时更改的DbContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!