参考Point connectionstring in dbml to app.config
如何使用参数替换部分类中的连接名称,以便可以切换连接字符串?
答案 0 :(得分:0)
如果您使用的是实体框架,则可以使用此类
public static void ChangeDatabase(
this DbContext source,
string initialCatalog = "",
string dataSource = "",
string userId = "",
string password = "",
bool integratedSecuity = true,
string configConnectionStringName = "",
string sqlConnectionString = "")
/* this would be used if the
* connectionString name varied from
* the base EF class name */
{
try
{
// use the const name if it's not null, otherwise
// using the convention of connection string = EF contextname
// grab the type name and we're done
var configNameEf = string.IsNullOrEmpty(configConnectionStringName)
? source.GetType().Name
: configConnectionStringName;
// add a reference to System.Configuration
var entityCnxStringBuilder = new EntityConnectionStringBuilder
(System.Configuration.ConfigurationManager
.ConnectionStrings[configNameEf].ConnectionString);
// init the sqlbuilder with the full EF connectionstring cargo
var sqlCnxStringBuilder = new SqlConnectionStringBuilder
(entityCnxStringBuilder.ProviderConnectionString);
if (string.IsNullOrEmpty(sqlConnectionString))
{
// only populate parameters with values if added
if (!string.IsNullOrEmpty(initialCatalog))
sqlCnxStringBuilder.InitialCatalog = initialCatalog;
if (!string.IsNullOrEmpty(dataSource))
sqlCnxStringBuilder.DataSource = dataSource;
if (!string.IsNullOrEmpty(userId))
sqlCnxStringBuilder.UserID = userId;
if (!string.IsNullOrEmpty(password))
sqlCnxStringBuilder.Password = password;
// set the integrated security status
sqlCnxStringBuilder.IntegratedSecurity = integratedSecuity;
sqlConnectionString = sqlCnxStringBuilder.ConnectionString;
}
// now flip the properties that were changed
source.Database.Connection.ConnectionString
= sqlConnectionString;
}
catch (Exception ex)
{
// set log item if required
}
}
并使用以下
调用此类dbContext = new ORM.CustomyzerEntities();
this._destDBContext.ChangeDatabase(
sqlConnectionString: connectionstringname);
此处将connectionstringname
替换为您的连接字符串