Reputation: 23187
I basically have two different databases that have different tables in them, but they both have "Table1" with the exact same structure.
var db = new ???;
if(mode == "PRODUCTION"){
db = new Database1("Connection string for Database1");
}
else{
db = new Database2("Connection string for Database2");
}
var result = db.Table1.Where(a=>a.Value==1).First();
How can I make the above work so I can assign "result" from two different databases (depending on "mode") without writing two different definitions for "result"?
Upvotes: 0
Views: 206
Reputation: 70523
Justin's point is a good one, here is another -
Why do this at the db level?
Something like this would work
var table;
if(mode == "PRODUCTION"){
db = new Database1("Connection string for Database1");
table = db.table1;
}
else{
db = new Database1("Connection string for Database2");
table = db.table1
}
var result = table.Where(a=>a.Value==1).First();
If you don't have the same exact db then you would need to do something like this (you could also add an interface to db1 and db2 to return commonElements -- as you wish.
class commonElements {
/// some code
}
public commoneElements GetCommon(Database1 inDB1) {
/// some code
}
public commoneElements GetCommon(Database2 inDB2) {
/// some code
}
commonElements common;
if(mode == "PRODUCTION"){
db1 = new Database1("Connection string for Database1");
common = GetCommon(db1);
}
else{
db2 = new Database2("Connection string for Database2");
common = GetCommon(db2);
}
var result = common.Where(a=>a.Value==1).First();
Upvotes: 2
Reputation: 245419
Store the connection strings separately in your config file. You can then swap the connection strings at runtime to point the database object to the right database:
if(mode == "PRODUCTION")
{
db = new Database(ConfigurationManager.ConnectionStrings["production-key"]);
}
else
{
db = new Database(ConfigurationManager.ConnectionStrings["dev-key"]);
}
Upvotes: 3