[英]How I can change the database name in DataContext
I created the code which fine work with my production database. 我创建了与生产数据库一起使用的代码。 But I want easy way for changing database name.
但我希望方便地更改数据库名称。 It is way will be without further action, and code duplication.
它是没有进一步行动和代码重复的方式。 How I can do it?
我怎么能这样做?
I having databeses "MyDB_1", "MyDB_2" - it is full of copies of databases for testing and like that. 我有数据库“MyDB_1”,“MyDB_2” - 它充满了用于测试的数据库副本。
The way to change the connection via ODBC is also nice. 通过ODBC更改连接的方法也很好。 But how i can do it?
但我怎么做呢?
DataTrackerClassesDataContext ctx = new DataTrackerClassesDataContext();
// !!! I cant change the property because it's readonly:
//ctx.Connection.Database = "MyDB_1";
//ctx.Connection.Database = "MyDB_2";
Console.WriteLine(ctx.Connection.Database);
var custQuery =
from m in ctx.models
where m.status == 1
select m.id;
foreach (int id in custQuery)
{
Console.WriteLine("{0} ", id);
}
If you want to switch the database for a datacontext, then in the constructor for a datacontext you would input the new connection string. 如果要为datacontext切换数据库,则在datacontext的构造函数中输入新的连接字符串。
You would do it like this to maintain the format: 您可以像这样保持格式:
string connectionString =
string.Format("Data Source={0};Initial Catalog={1};Integrated Security=True",
serverName,
dataBaseName);
DataTrackerClassesDataContext ctx = new DataTrackerClassesDataContext(connectionString);
And you would just replace the connection string based on which database you wanted to use. 您只需根据要使用的数据库替换连接字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.