C# 将EF6与MySQL和SQL Server一起使用

C# 将EF6与MySQL和SQL Server一起使用,c#,entity-framework-6,C#,Entity Framework 6,我有一个同时使用SQL Server和MySQL数据库的项目。我随后将MySQL与EF6一起使用,效果非常好 然后,我又添加了一个连接到SQL Server的DbContext(EfContext)。每当我在此上下文中执行任何命令时,都会引发异常: 未处理的异常:System.Data.Entity.Core.ProviderIncompatibleException:提供程序未返回ProviderManifestToken字符串 MySql.Data.MySqlClient.MySqlExce

我有一个同时使用SQL Server和MySQL数据库的项目。我随后将MySQL与EF6一起使用,效果非常好

然后,我又添加了一个连接到SQL Server的
DbContext
EfContext
)。每当我在此上下文中执行任何命令时,都会引发异常:

未处理的异常:System.Data.Entity.Core.ProviderIncompatibleException:提供程序未返回ProviderManifestToken字符串

MySql.Data.MySqlClient.MySqlException:无法连接到任何指定的MySql主机

同样的问题,没有解决办法

我调试并发现
MssqlDbContext
的连接是
MySql.Data.MySqlClient.MySqlConnection
,无论我的提供者名称是
System.Data.SqlClient
。似乎
MySqlEFConfiguration
覆盖了所有配置

我的问题还有其他解决办法吗

[更新]

我把两个类库分开

  • SQL Server:仅引用EF和EF.SQL(EfContext)
  • Mysql:仅引用EF和Mysql.Data.Entity(MySqlContext)
在演示项目中

app.config

<connectionStrings>
    <add name="EfContext" 
         connectionString="..." 
         providerName="System.Data.SqlClient" />
    <add name="MySqlContext" 
         connectionString="..." 
         providerName="MySql.Data.MySqlClient" />
</connectionStrings>

<entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <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" />
    </providers>
</entityFramework>
例外情况:

未处理的异常:System.TypeInitializationException:“MySql.Context.MySqlContext”的类型初始值设定项引发了异常

System.InvalidOperationException:在发现“MySqlEFConfiguration”类型之前,实体框架使用了默认的DbConfiguration实例。在使用任何实体框架功能之前,必须在应用程序启动时设置“MySqlEFConfiguration”的实例,或者必须在应用程序的配置文件中注册。有关更多信息,请参阅

案例2:在EfContext之前调用MySqlContext

var mysql = new MySqlContext("name=MySqlContext");
var ef = new EfContext("name=EfContext");
ef.Database.ExecuteSqlCommand("...");
例外情况:

未处理的异常:System.Data.Entity.Core.ProviderIncompatibleException:提供程序未返回ProviderManifestToken字符串

MySql.Data.MySqlClient.MySqlException:无法连接到任何指定的MySql主机。-->System.AggregateException:发生一个或多个错误。-->System.Net.Sockets.SocketException:未知此类主机


SQL Server使用类SQLClient而不是MySqlClient。错误消息显示MySqlClient。这是一个问题。无论我将其配置为MSSQL,所有连接都会更改为MySql。我们需要查看您的代码,显然您需要使用不同的
DLL
,一个是
MySql.Dal.EF
,另一个是
MSSQL.Dal.EF
我更新了我的问题您使用的是什么版本的VS?您是否将“using System.Data.SqlClient”添加到模块顶部?
var mysql = new MySqlContext("name=MySqlContext");
var ef = new EfContext("name=EfContext");
ef.Database.ExecuteSqlCommand("...");