1: Make two contexts: one of users, the other of tables of the system
I think the idea is to have all the same contexts, with just the 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 only stores 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 keep the Connection Strings
.
2: Implement a ActionFilter
which determine 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. Recover the 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
}
}
}
the idea is good...but I will do a little different, in a simple connection user -> company, where the same will have only the name of the bank, so the 1 context does the login and passes the name of the bank to the second context, so the 1 context is only for login and user info and the second, What do you think? I’ve been up all night thinking about it, rsrsr
– Rod
@Rod yes, that’s exactly what my answer puts. You can perfectly change the
Connection String
of the example to put the name of this bank, and configure theWeb.config
to have theConnection Strings
. What would change is the way you start the context, where you pass the name of the connection as argument, not the connection itself.– Leonel Sanches da Silva