c# - Switch between databases with one DbContext -


i'm working on developing web application having several databases same schema. depends on logged in user database execute queries may differ.

i'm planning have connection string each db , when executing query in repository level change connection string when db context creating.

my problem i've tried pass connection string name db context dynamically before executing linq query, failed.

would grate if can me on doing , let me know pros , cons in approach.

you can add overload db context constructor accepts connection string input:

public partial class sampledbentities {     public sampledbentities(string connectionstring)         : base(connectionstring)     {     } } 

then when need create instance of db context, use overload , inject suitable username , password in connection string:

for example when connection string looks this:

var connectiontemplate = @"provider=system.data.sqlclient;" +                        @"provider connection string=""data source={0};" +                        @"initial catalog=servername;persist security info=true;" +                        @"user id={1};password={2};" +                        @"multipleactiveresultsets=true;app=entityframework"""; 

then can use string.format(connectiontemplate, databasename, username, password) create connection string , pass constructor of db context;

//you provide databasename, username, password based on logic //for example based on user logged in application. var connectionstring= string.format(connectiontemplate, databasename, username, password); var db = new sampledbentities(connectionstring); 

Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -