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

左心房为你撑大大i 提交于 2019-12-06 07:16:34

问题


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:


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());



回答2:


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

public DbContext(
string nameOrConnectionString,
DbCompiledModel model
)



回答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.



来源:https://stackoverflow.com/questions/14480646/how-to-have-different-connection-string-for-different-users-in-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!