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 } }
这是一个多用户数据库,我们有3个不同的数据库。集中DB位于公共位置,不会更改。这是DB存储的其他细节。我需要创建连接字符串@运行时,其细节将来自此集中式数据库。有人可以让我知道怎么去吗?
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 express,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); } }