Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have different connection string for different users in Entity Framework

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

like image 612
Syed Mohd Mohsin Akhtar Avatar asked Dec 12 '22 18:12

Syed Mohd Mohsin Akhtar


2 Answers

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());
like image 154
Syed Mohd Mohsin Akhtar Avatar answered May 08 '23 04:05

Syed Mohd Mohsin Akhtar


You could use the following DbContext constructor which accepts the connections string or name as an argument.

public DbContext(
string nameOrConnectionString,
DbCompiledModel model
)
like image 40
Kevin Junghans Avatar answered May 08 '23 02:05

Kevin Junghans