我正在尝试使用实体框架代码第一个模型连接多个数据库提供程序,通过动态生成连接字符串。但它没有按预期工作。
以下是要审核的代码:
switch (providerName)
{
case "System.Data.SqlClient":
entityBuilder = new EntityConnectionStringBuilder();
entityBuilder.Provider = providerName;
//ConfigurationManager.ConnectionStrings["mssql"].ConnectionString
break;
case "MySql.Data.MySqlClient":
entityBuilder = new EntityConnectionStringBuilder();
entityBuilder.Provider = providerName;
//ConfigurationManager.ConnectionStrings["mysql"].ConnectionString
break;
default:
break;
}
switch (providerName)
{
case "System.Data.SqlClient":
conn = new SqlConnectionStringBuilder(entityBuilder.ProviderConnectionString)
{
UserID = databaseUserId,
Password = databasePassword,
DataSource = serverName,
IntegratedSecurity = false,
InitialCatalog = databaseName
}.ConnectionString;
break;
case "MySql.Data.MySqlClient":
conn = new MySql.Data.MySqlClient.MySqlConnectionStringBuilder(entityBuilder.ProviderConnectionString)
{
Server = serverName,
UserID = databaseUserId,
Password = databasePassword,
Database = databaseName,
PersistSecurityInfo = true
}.ConnectionString;
break;
default:
break;
}
Web.config
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6, Version=6.9.9.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"></provider></providers>
</entityFramework>
<DbProviderFactories>
<remove invariant="MySql.Data.MySqlClient" />
<add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.9.9.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
</DbProviderFactories>
DbContext构造函数
` public partial class ModelCodeFist : DbContext
{
public ModelCodeFist(string connection)
: base(connection)
{
}
}
`
另外如何在运行时更改默认提供程序,因为EF将sql连接器作为defaultConnectionFactory
动态连接到mssql正在运行,但是对于 mysql,它产生错误,因为默认连接器仍然是sqlclient ,请查看下面的图片:
如果我错过了什么,请告诉我 谢谢!
答案 0 :(得分:0)
您想要创建自己的ProviderFactory,实现IDbConnectionFactory
public class MyProviderFactory : IDbConnectionFactory
{
public DbConnection CreateConnection(string nameOrConnectionString)
{
if ("mySqlName".equals(nameOrConnectionString))
{
return new MySqlConnection("<Connection String>");
}
else
{
return new SqlConnection("<Connection String>");
}
}
}
然后在app.config中将其设置为DefaultConnectionFactory
<defaultConnectionFactory type="MyAssmebly.MyProviderFactory, MyAssmebly">
<parameters>
未经过测试的代码,当然没有经过性能测试!