Use MySQL and MSSQL in Entity Framework 6

I am developing a web service.

Two methods are used for this service: One for getting entities from MySQL Connection, and the other for getting objects from a connection to the MSSQL server.

I have two connection strings.

I would like to have two contexts, they are completely separate.

But I can't handle it.

Any ideas?

+1
source share
1 answer

In the end, the solution was simple.

Be sure to install MySql Connector / Net on all target systems! I missed this on my target platform.

web.config / app.config:

<configuration>
  <configSections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>
    <add name="MsSqlServerContext" connectionString="MSSQLCONNECTIONSTRING" providerName="System.Data.SqlClient" />
    <add name="MySqlServerContext" connectionString="MYSQLCONNECTIONSTRING" providerName="MySql.Data.MySqlClient" />
  </connectionStrings>
  <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" />
    </providers>
  </entityFramework>
</configuration>

MsSqlServerContext.cs

public partial class MsSqlServerContext : DbContext
{
    public MsSqlServerContext()
        : base("name=MsSqlServerContext")
    {
        Database.SetInitializer<MsSqlServerContext>(null);
    }

    // Add DbSets here
    public DbSet<ClassName1> SomeName1 { get; set; }
    public DbSet<ClassName2> SomeName2 { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // Add Mappings here
        modelBuilder.Configurations.Add(new ClassName1Map());
        modelBuilder.Configurations.Add(new ClassName2Map());
    }
}

MySqlServerContext

public partial class MySqlServerContext : DbContext
{
    public MySqlServerContext()
        : base("name=MySqlServerContext")
    {
        Database.SetInitializer<MySqlServerContext>(null);
    }

    public DbSet<ClassName3> SomeName3 { get; set; }
    public DbSet<ClassName4> SomeName4 { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new ClassName3Map());
        modelBuilder.Configurations.Add(new ClassName4Map());
    }
}
+2
source

Source: https://habr.com/ru/post/1539544/


All Articles