33

In my solution I have 2 projects that use Entity Framework 6. Each points to a different database, both using the same data provide - SQL Server. A third project in my solution needs to use both databases. My problem is how to configure those context. I tried to create a configuration class in a separate assembly:

namespace OSAD_Base
{
    class EfDbConfiguration : DbConfiguration
    {
        public EfDbConfiguration()
        {
            SetProviderServices(SqlProviderServices.ProviderInvariantName, SqlProviderServices.Instance);
        }
    }
}

and referencing to this configuration in each context class:

namespace IntegrationDb
{
    [DbConfigurationType("OSAD_Base.EfDbConfiguration, OSAD_Base")]
    public partial class IntegrationEntities : DbContext
    {
        public IntegrationEntities(string connectionString)
            : base(connectionString)
        {
        }
    }
}

When initializing my first, all works correct, but when the second context initializes (Order does not matter) I get and error:

An instance of 'EfDbConfiguration' was set but this type was not discovered in the same assembly as the 'B1Entities' context. Either put the DbConfiguration type in the same assembly as the DbContext type, use DbConfigurationTypeAttribute on the DbContext type to specify the DbConfiguration type, or set the DbConfiguration type in the config file. See http://go.microsoft.com/fwlink/?LinkId=260883 for more information.*

I also tried to create an entityframework section in my app.config (of the start up project) but got the following error:

Configuration system failed to initialize

Unrecognized configuration section entityFramework

How can I use 2 separate EF Projects in the same solution?

Community
  • 1
  • 1
Motty
  • 579
  • 1
  • 6
  • 9

3 Answers3

31

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

Yaser Moradi
  • 3,267
  • 3
  • 24
  • 50
  • I have no issues with connectin string. That works just fine. The problem is to define the provide for the context. Trying to add the entity framework in the app.config of the start up project, results in an error, as entity framework is not even referenced there. Adding the following tag: code – Motty Dec 02 '13 at 17:10
  • Please see my post above – Motty Dec 02 '13 at 17:24
  • It was same provider with AppDb, AnotherDb but two or more providers has multiple Configuration class I was imposibble that explain under link "Moving DbConfiguration" section. http://msdn.microsoft.com/en-us/data/jj680699.aspx There are cases where it is not possible to place your DbConfiguration class in the same assembly as your DbContext class – Kim Ki Won May 22 '14 at 03:00
  • 16
    Does not answer the question at all. – Kugel Feb 13 '15 at 03:47
  • 2
    This answer satisfies me will answering the "Title" thus this answer works for me just fine. – Tom Stickel Aug 22 '15 at 00:14
  • 1
    @Kugel Question: Two db context in two different projects. How can I configure their connections? Answer: It doesn't matter how many projects you've and where are those classes. Just define 2 connection strings in app.config or web.config of startup project and use connection string name in db context classes. You can use same or different database for each db context and you can even use different database engines. So, How can you say it doesn't answer the question at "all"? – Yaser Moradi Jul 14 '19 at 20:13
10

Connection string of EntityFramework 6 should be inside configuration file that located (alert!) in execution folder. For example OP have multiple projects in solution, so the connection string must be in configuration file belongs to main executive project.

Now, if you want to define connection string in your code, you can make fake connection string in configuration file and give your entity's instance new connection string:

DBEntities e = new DBEntities();
e.Database.Connection.ConnectionString = "Data Source=MyServ;Initial Catalog=MyDB;Persist Security Info=True;User ID=sa;Password=***;Application Name=MyApp";
Nexaspx
  • 371
  • 4
  • 20
Rodion
  • 886
  • 10
  • 24
0

Here is what I did for two DB with EF6

Web.config

      <connectionStrings>
        <add name="EntityContainer" connectionString="metadata=res://WebService/Database.Database.csdl|res://WebService/Database.Database.ssdl|res://WebService/Database.Database.msl; .../>
        <add name="ArchiveEntityContainer" connectionString="metadata=res://WebService/Database.Database.csdl|res://WebService/Database.Database.ssdl|res://WebService/Database.Database.msl; .../>
      </connectionStrings>

Add second constructor in Database.Context.tt (be careful: auto-generated code)

public <#=code.Escape(container)#>(string connectionString)
    : base(connectionString)
{
}

Use

using (EntityContainer context = new EntityContainer())
{
    //...
}

using (EntityContainer context = new EntityContainer("ArchiveEntityContainer"))
{
    //...
}
codeepic
  • 3,723
  • 7
  • 36
  • 57
Flou
  • 93
  • 1
  • 9
  • 3
    This will break whenever the EF templates are re-run. For a more robust way to do this, see [this blog post by Olivier Hélin](http://olivierhelin.com/blog/entity-framework/entity-framework-6-one-entity-data-model-multiple-databases-2) – Aaroninus Oct 29 '19 at 12:44