sql server - Using DbContext dynamically -
i have multiple dbs with identical schema. in code, query 1 of dbs parameter, change dynamically.
now looks this:
public void savenewuser(user user, string type) { if (type == "a") { using (var db = new aentities()) { db.users.add(user); db.savechanges(); } } else { using (var db = new bentities()) { db.users.add(user); db.savechanges(); } } }
instead, this:
public void savenewuser(user user, string type) { using (var db = new generalentity(type)) { db.users.add(user); db.savechanges(); } }
any ideas?
in experience, have 1 dbcontext solve similar problems. modify connection string @ runtime. entity framework supports allowing call constructor connection string.
i allow administrators maintain settings profiles, given model, application stores collection of encrypted sql settings. @ runtime, list loaded dictionary profile name ("a", "b") serving keys.
then use dbcontext constructor expects connection string , pass built connection string based on target db:
// model name in app.config connection string (any model name - model1?) private string buildconnectionstring(string profile) { // configuration hold collection of settings - prefer provide var settings = configuration.getconnectionsettings(profile); // build provider connection string configurable settings var providersb = new sqlconnectionstringbuilder { initialcatalog = settings.initialcatalog, datasource = settings.datasource, userid = settings.user, password = settings.password }; var efconnection = new entityconnectionstringbuilder(); // or config file based connection without provider connection string // var efconnection = new entityconnectionstringbuilder(@"metadata=res://*/model1.csdl|res://*/model1.ssdl|res://*/model1.msl;provider=system.data.sqlclient;"); efconnection.provider = "system.data.sqlclient"; efconnection.providerconnectionstring = providersb.connectionstring; // based on whether choose supply app.config connection string constructor efconnection.metadata = "res://*/model.dbentities.csdl|res://*/model.dbentities.ssdl|res://*/model.dbentities.msl", model; return efconnection.tostring(); }
then in example, use 1 dbcontext:
using (var db = new dbentities(buildconnectionstring("a"))) { db.users.add(user); db.savechanges(); }
Comments
Post a Comment