MaT
MaT

Reputation: 1606

Changing dbContext at runtime

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());
   }
}

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);
}

The db's connectionString is associated to the dbA not the dbB. Why the new db is not well initilized and saved ?

Upvotes: 0

Views: 1374

Answers (1)

Eranga
Eranga

Reputation: 32437

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());
   }
}

Upvotes: 1

Related Questions