3

I want to encapsulate Entity Framework in one project. This project will do DB access alone. When updating, I want to map a domain model to EF. The purpose is that other layers of the solution should have no knowledge of infrastructure.

My problem is that I need to reference EF in my "caller" project to make it work.

Is there a way to avoid this?

Solution - ConsoleProject - EntityFrameworkProject (EF from Nuget)

redlaz
  • 121
  • 3
  • 9
  • 3
    Have you tried Repository design pattern with Unit Of Work ? – captainsac Apr 29 '15 at 10:47
  • 2
    if you generate your POCO objects for EF in your repository project, you only need a reference to this project and no EF reference is required in your "caller project"? – Vincent De Smet Apr 29 '15 at 10:50
  • Create project responsible for database connection and create repositories (Unit Of Work is also good idea). Create some interfaces with DTOs and your other projects shouldn't contain reference to EF. – Marcin J Apr 29 '15 at 10:53

3 Answers3

3

With EF6 and code based configurations, this is now possible.

[DbConfigurationType(typeof(MyDbContextConfiguration))]
internal class MyDbContext : DbContext
{
    public DbSet<MyModel> MyModels { get; set; }
}

internal class MyDbContextConfiguration : DbConfiguration
{
    public MyDbContextConfiguration()
    {
        SetProviderServices("System.Data.SqlClient", SqlProviderServices.Instance);
    }
}

If you configure your database in Project A as above, then only Project A needs to reference EntityFramework, and any project that references it, like Project B will not try to find the provider in its own assembly.

Expose your repositories in Project A, and add a <connectionStrings> configuration in Project B, and it should work flawlessly.

René Sackers
  • 2,395
  • 4
  • 24
  • 43
1

I used this approach: https://stackoverflow.com/a/22970805/3874212

  1. I reference the EntityFramework.SqlServer.dll only in the Console startup project.
  2. I install entity Framework in my other project.
  3. I create my model from DB in EF project
  4. I move the connection string from the app.config in EF project to the Console project.
Community
  • 1
  • 1
redlaz
  • 121
  • 3
  • 9
0

Unfortunately it is not possible for some strange reason. You must include EF package in client application too, not only in data access library.
It is possible to include only that DLL redlaz mentioned, but by doing this you are cooking lot of potential problems with versions.
Just overcome all reluctance and add EF package to your client application too.

Ondřej
  • 1,645
  • 1
  • 18
  • 29