在运行时更改的DbContext [英] Changing dbContext at runtime

查看:144
本文介绍了在运行时更改的DbContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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屋!

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