0

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 ?

1 Answer 1

1

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()); } } 
Sign up to request clarification or add additional context in comments.

2 Comments

It's a good idea but the Session is always null in Controller Constructor.
@MaT move the logic in the constructor to Initialize method.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.