1: Make two contexts: one of users, another of system tables
I think the idea is to have all contexts equal, with only Connection String
different. In this case, it is interesting to have a common context:
public class MeuContexto : DbContext
{
public MeuContexto(String connectionString) : base(connectionString)
{ }
// Coloque seus DbSets aqui
}
And another context that stores only user data:
public class UsersContext : DbContext
{
public MeuContexto() : base("DefaultConnection")
{ }
// Coloque seus DbSets de usuário aqui
}
In this user context, you can have a Model that stores the Connection Strings
.
2: Implement a ActionFilter
that determines which Connection String
will be used
public class CustomActionFilter : ActionFilterAttribute, IActionFilter
{
void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
{
var usersContext = new usersContext();
var user = usersContext.Users.SingleOrDefault(u => u.Name == User.Identity.Name);
filterContext.HttpContext.Items["connectionString"] = user.Company.ConnectionString;
this.OnActionExecuting(filterContext);
}
}
3. Retrieve Connection String
within your Action
In this case, you will have to start a context for each Action
.
[CustomActionFilter]
public class MeuController : Controller
{
public ActionResult Index()
{
using (var context = new MeuContexto(HttpContext.Items["connectionString"].ToString()))
{
// Use seu contexto aqui normalmente
}
}
}