4

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

1

3 Answers 3

6

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

Comments

4

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

public DbContext(
string nameOrConnectionString,
DbCompiledModel model
)

Comments

3

I dont know which is specifically your question, its not about MVC its only for EF.

If I understand correctly what you want to do, you probably have separeted databases for each user, but you have only ONE database for the users account information for login

You can add one more field to that database, the users login databse, with the specific connectionString for that user. Then when you login the user use the DbContext for that databse and login, then get the value for the connectionString and generate the new DbContext for the specific database for the user loged in.

If you need more help please comment.

1 Comment

I don't have different databases for different user but rather different privilege for different users

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.