实体框架在运行时更改连接 [英] Entity Framework change connection at runtime
问题描述
我建立了如下连接字符串:
public void Connect(数据库数据库)
{
//构建SQL连接字符串
SqlConnectionStringBuilder sqlString = new SqlConnectionStringBuilder()
{
DataSource = database.Server,
InitialCatalog = database.Catalog,
UserID = database.Username,
Password = database.Password,
};
//构建一个实体框架连接字符串
EntityConnectionStringBuilder entityString = new EntityConnectionStringBuilder()
{
Provider = database.Provider,
Metadata = Settings。 Default.Metadata,
ProviderConnectionString = sqlString.ToString()
};
}
首先,我如何实际改变数据上下文的连接?
其次,由于这是一个Web API项目,所以连接字符串(在上面登录时设置)在用户交互中持续存在,或者每次都要传递给我的数据上下文?
这个答案有点迟了,但我认为有一个潜在的方法来做一个整洁的小扩展方法。我们可以利用EF配置加上几个框架调用。
无论如何,注释的代码和示例用法:
扩展方法类:
public static class ConnectionTools
{
// all params是可选的
public static void ChangeDatabase(
this DbContext source,
string initialCatalog =,
string dataSource =,
string userId =
string password =,
bool integratedSecuity = true,
string configConnectionStringName =)
/ *如果
* connectionString名称从
*基础EF类名* /
{
try
{
//如果它不为空,则使用const名称,否则
//使用连接字符串的约定= EF contextname
//获取类型名称a d我们完成
var configNameEf = string.IsNullOrEmpty(configConnectionStringName)
? source.GetType()。Name
:configConnectionStringName;
//添加对System.Configuration的引用
var entityCnxStringBuilder = new EntityConnectionStringBuilder
(System.Configuration.ConfigurationManager
.ConnectionStrings [configNameEf] .ConnectionString);
//初始化具有完整EF连接字符串货物的sqlbuilder
var sqlCnxStringBuilder = new SqlConnectionStringBuilder
(entityCnxStringBuilder.ProviderConnectionString);
//仅在添加
时填充参数(如果(!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;
//设置集成安全状态
sqlCnxStringBuilder.IntegratedSecurity = integratedSecuity;
//现在翻转已更改的属性
source.Database.Connection.ConnectionString
= sqlCnxStringBuilder.ConnectionString;
}
catch(Exception ex)
{
//设置日志项目如果需要
}
}
}
基本用法:
//假定.config中的一个connectionString名称为MyDbEntities
var selectedDb = new MyDbEntities();
//所以只引用更改的属性
//使用对象参数名称
selectedDb.ChangeDatabase
(
initialCatalog:name-of-another-initialcatalog ,
userId:jackthelady,
密码:nomoresecrets,
dataSource:@。\sqlexpress//可以是ip地址120.273.435.167等
) ;
我知道你已经有基本的功能,但是认为这会增加一点点多样性。 / p>
I have a web API project which references my model and DAL assemblies. The user is presented with a login screen, where he can select different databases.
I build the connection string as follows:
public void Connect(Database database)
{
//Build an SQL connection string
SqlConnectionStringBuilder sqlString = new SqlConnectionStringBuilder()
{
DataSource = database.Server,
InitialCatalog = database.Catalog,
UserID = database.Username,
Password = database.Password,
};
//Build an entity framework connection string
EntityConnectionStringBuilder entityString = new EntityConnectionStringBuilder()
{
Provider = database.Provider,
Metadata = Settings.Default.Metadata,
ProviderConnectionString = sqlString.ToString()
};
}
First of all, how do I actually change the connection of the data context?
And secondly, as this is a web API project, is the connection string (set at login per above) persistent throughout the user's interaction or should it be passed every time to my data context?
A bit late on this answer but I think there's a potential way to do this with a neat little extension method. We can take advantage of the EF convention over configuration plus a few little framework calls.
Anyway, the commented code and example usage:
extension method class:
public static class ConnectionTools
{
// all params are optional
public static void ChangeDatabase(
this DbContext source,
string initialCatalog = "",
string dataSource = "",
string userId = "",
string password = "",
bool integratedSecuity = true,
string configConnectionStringName = "")
/* 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);
// 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;
// now flip the properties that were changed
source.Database.Connection.ConnectionString
= sqlCnxStringBuilder.ConnectionString;
}
catch (Exception ex)
{
// set log item if required
}
}
}
basic usage:
// assumes a connectionString name in .config of MyDbEntities
var selectedDb = new MyDbEntities();
// so only reference the changed properties
// using the object parameters by name
selectedDb.ChangeDatabase
(
initialCatalog: "name-of-another-initialcatalog",
userId: "jackthelady",
password: "nomoresecrets",
dataSource: @".\sqlexpress" // could be ip address 120.273.435.167 etc
);
I know you already have the basic functionality in place, but thought this would add a little diversity.
这篇关于实体框架在运行时更改连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!