Configure multiple database Entity Framework 6

It’s not important that how many DbContexts you have(In entity framework 6).
Just put connection strings in appConfig or webConfig of startup project.

Then you’re ready to go.

Example of appConfig with two connectionString with Ef 6.01 & Sql Compact 4.0

<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="MainDb" connectionString="Data Source=|DataDirectory|\Db.sdf" providerName="System.Data.SqlServerCe.4.0" />
    <add name="AnotherDb" connectionString="Data Source=|DataDirectory|\AnotherDb.sdf" providerName="System.Data.SqlServerCe.4.0" />
  </connectionStrings>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlCeConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="System.Data.SqlServerCe.4.0" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlServerCe.4.0" type="System.Data.Entity.SqlServerCompact.SqlCeProviderServices, EntityFramework.SqlServerCompact" />
    </providers>
  </entityFramework>

And example of DbContexts:

public class AppDb : DbContext
{
    public AppDb()
        : base("MainDb")
    {

    }
}

public class AnotherDb : DbContext
{
    public AnotherDb()
        : base("AnotherDb")
    {

    }
}

It’s not important that your contexts are in separated projects or not, only Config of startup project is important.

Let me know if any other information you need.

Good luck

Leave a Comment