Rody
Rody

Reputation: 2655

How to remove references to Entity Framework in other layers

I have an application with 3 layers:

The Data layer uses EF 6 (code first) to connect to the database.

I've create an interface which my DbContext implements:

public interface IMyDbContext
{
    DbSet<TEntity> Set<TEntity>() where TEntity : class;
    int SaveChanges();
    void Dispose();
}

public class MyDbContext : DbContext, IMyDbContext
{
    //...
    public DbSet<Account> Accounts { get; set; }
    public DbSet<Module> Modules { get; set; }
    public DbSet<User> Users { get; set; }
    //...
}

I want to remove the references to EF from the Domain Services layer, that's why I inject this Interface into the Domain Services layer using Dependency Injection.

However the DbSet class is described in the EF binaries, so this is not going to work.

I'd like to use this abstraction in stead of the actual EF implementation, but I'm stuck. I've tried using IQueryable in stead of DbSet, but this didn't work.

I don't want to use (Generic) Repositories, but I want to re-use the DbSet and DbContext functionality of EF in my domain logic.

Upvotes: 1

Views: 1148

Answers (2)

Silas Reinagel
Silas Reinagel

Reputation: 4223

A good solution is to use the Repository Pattern (along with Unit of Work) and create one more abstraction of Repository< T >.

http://www.codeproject.com/Articles/526874/Repositorypluspattern-cplusdoneplusright

Upvotes: 1

nikis
nikis

Reputation: 11254

What you are looking for is Unit of Work pattern. It will help you to prevent leaking data logic to the domain layer. Here is a nice tutorial on that.

Upvotes: 3

Related Questions