I have a requirement in which I need to have different connection strings for different users. The idea is to have the username
and password
supplied at the login screen to be used as the username
and password
of the connection string. Thus making application to use different connection string for different user, and to use this connection string throughout the application.
How to get this setup in EF 4.1
PS: I am using DbContext
Thanks to Kevin Junghans
This is how I have done it.
in the model context class
public class MyEntities : DbContext
{
public MyEntities (string connectionString)
: base(connectionString)
{
}
then in the login controller
var dataConnection = WebConfigurationManager.OpenWebConfiguration("/").ConnectionStrings.ConnectionStrings["MyConnectionString"].ConnectionString;
dataConnection = dataConnection.Substring(0, dataConnection.LastIndexOf("\"")) + ";USER ID=" + userName +";Password=" + password + "\"";
Session["connectionString"] = dataConnection;
and the from else where
var _db = new MyEntities (Session["connectionString"].ToString());
You could use the following DbContext constructor which accepts the connections string or name as an argument.
public DbContext(
string nameOrConnectionString,
DbCompiledModel model
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With