EF6的DbContext动态连接字符串
作者:互联网
问 题:
public partial class ProcessContext : DbContext { static ProcessContext() { Database.SetInitializer<ProcessContext>(null); } public ProcessContext() : base("Name=ProcessCS") //Comes from Config File { } --DBSets protected override void OnModelCreating(DbModelBuilder modelBuilder) { --Code } }
我试着用下面的code,但它不工作。该方法如下
public ProcessContext() : base(nameOrConnectionString: ConnectionString()) { } private static string ConnectionString() { SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder(); sqlBuilder.DataSource = "XXX"; sqlBuilder.InitialCatalog = "YYY"; sqlBuilder.PersistSecurityInfo = true; sqlBuilder.IntegratedSecurity = true; sqlBuilder.MultipleActiveResultSets = true; EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder(); entityBuilder.ProviderConnectionString = sqlBuilder.ToString(); entityBuilder.Metadata = "res://*/"; entityBuilder.Provider = "System.Data.SqlClient"; return entityBuilder.ToString(); }
解决方案:
有关SQL Server连接,覆盖实体容器类:(开发环境:EF6中,SQL Server 2012的前preSS,VS2013)
public partial class PxxxxEntities
{
private PxxxxEntities(string connectionString)
: base(connectionString)
{
}
public static PxxxxEntities ConnectToSqlServer(string host, string catalog, string user, string pass, bool winAuth)
{
SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder
{
DataSource = host,
InitialCatalog = catalog,
PersistSecurityInfo = true,
IntegratedSecurity = winAuth,
MultipleActiveResultSets = true,
UserID = user,
Password = pass,
};
// assumes a connectionString name in .config of MyDbEntities
var entityConnectionStringBuilder = new EntityConnectionStringBuilder
{
Provider = "System.Data.SqlClient",
ProviderConnectionString = sqlBuilder.ConnectionString,
Metadata = "res://*/DbModel.csdl|res://*/DbModel.ssdl|res://*/DbModel.msl",
};
return new PxxxxEntities(entityConnectionStringBuilder.ConnectionString);
}
}
标签:sqlBuilder,string,EF6,entityBuilder,DbContext,字符串,new,true,public 来源: https://www.cnblogs.com/CelonY/p/12766954.html