我首先将连接字符串硬编码到实体框架数据库的 dbcontext 中。
public MirrorBranchesEntities(string connectionStringName, string db)
: base(@"name=" + connectionStringName + " connectionString=metadata=res://*/MirrorBranches.csdl|res://*/MirrorBranches.ssdl|res://*/MirrorBranches.msl;provider=System.Data.SqlClient;provider connection string=data source=(local);initial catalog=" + db + ";user id=sa;password=Qwer0987;MultipleActiveResultSets=True;App=EntityFramework; providerName=System.Data.EntityClient")
{
}
有多个数据库使用该连接字符串。问题是它返回异常
System.ArgumentException:不支持关键字:“初始目录”。
在 System.Data.Entity.Core.EntityClient.Internal.DbConnectionOptions.ParseInternal(哈希表可解析,字符串连接字符串,哈希表同义词)
在 System.Data.Entity.Core.EntityClient.Internal.DbConnectionOptions..ctor(字符串连接字符串,哈希表同义词)
在 System.Data.Entity.Core.EntityClient.EntityConnection.ChangeConnectionString(字符串 newConnectionString)
在 System.Data.Entity.Core.EntityClient.EntityConnection..ctor(字符串连接字符串)
在 System.Data.Entity.Internal.LazyInternalConnection.Initialize()
在 System.Data.Entity.Internal.LazyInternalConnection.CreateObjectContextFromConnectionModel()
在 System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
在 System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(类型实体类型)
在 System.Data.Entity.Internal.Linq.InternalSet1.Initialize()
at System.Data.Entity.Internal.Linq.InternalSet
1.get_InternalContext()
在 System.Data.Entity.Internal.Linq.InternalSet1.ActOnSet(Action action, EntityState newState, Object entity, String methodName)
at System.Data.Entity.Internal.Linq.InternalSet
1.添加(对象实体)
在 System.Data.Entity.DbSet`1.Add(TEntity 实体)
Update
我已经更新了我的连接字符串——去掉了双元数据属性并删除了额外的单引号
我正在尝试将连接字符串放入EntityConnectionStringBuilder
但无法将其插入上下文中。
public static MirrorBranchesEntities ConnectToSqlServer(string catalog)
{
var sqlBuilder = new SqlConnectionStringBuilder
{
DataSource = "(local)",
InitialCatalog = catalog,
PersistSecurityInfo = true,
IntegratedSecurity = true,
MultipleActiveResultSets = true,
UserID = "sa",
Password = "Qwer0987"
};
var entityConnectionStringBuilder = new EntityConnectionStringBuilder
{
Provider = "System.Data.EntityClient",
ProviderConnectionString = sqlBuilder.ConnectionString,
Metadata = "res://*/MirrorBranches.csdl|res://*/MirrorBranches.ssdl|res://*/MirrorBranches.msl",
};
return new MirrorBranchesEntities(entityConnectionStringBuilder.ConnectionString, sqlBuilder.InitialCatalog);
}
然后我将上下文更改为base(ConnectToSqlServer(connectionStringName,db))
但它说无效参数。