0

I'm trying to clean up this code but can't figure out the best way to go about it.

The UI will access the business layer and shouldn't know about EFContext in doing this I end up with an almost exact copy of the EFContext class in my RepoBase class. If I need a entity specific method, I'm creating a entity specific repo and deriving from the RepoBase

MS examples seem to skip the RepoBase and just implement each CRUD method in each and every entity, this seems like even more code duplication.

RepoBase does provide separation but at the cost of duplication. I would like to know if there's a better way.

Data Access Layer

public interface IDataContext
{
    T GetById<T>(int id);
    void Delete<T>(T entity);
}

public class EFContext : DbContext, IDataContext
{
    public virtual DbSet<Student> Student { get; set; }

    public T GetById<T>(int id)
    {
        ...
    }

    public void Delete<T>(T entity)
    {
        ...
    }

}

Business Logic Layer

// Generic repo
public class RepoBase
{
    private IDataContext _context;

    public RepoBase(IDataContext context)
    {
        _context = context;
    }

    public T GetById<T>(int id)
    {
        return _context.GetById<T>(id);
    }
}

// Specific repo
public class StudentRepo : RepoBase
{
    public Student GetByStudentId(int studentId)
    {
        ...
    }
}
  • What do you expect to gain by abstracting Entity Framework behind a repository? Some parts of your code might come out cleaner, but probably at the cost of fat repositories. – Rik D Aug 10 at 8:12
  • 3
    Good explanation on why should not implement repository pattern with entity framework: softwareengineering.stackexchange.com/a/220126/96627 – Roman Bats Aug 10 at 12:07
  • @RikD I guess this is the point that I'm missing. I start with my 3 layers (projects) and expect to fit something into each. Instead, it sounds like with EF I don't need a separate data access layer project. I'd just be tightly-bound to using EF and not able to swap out other ORMs – user3953989 Aug 10 at 18:09
  • DataContext is already a generic repository. If you’re worried about swapping ORMs later, implement a semantic data service layer with methods like GetFoo(int id) that can hide the details of how data access happens. – RubberDuck Aug 11 at 1:29
  • @RubberDuck I believe that's what I'm currently doing? My BLL is hiding the data access details, it's just causing code redundancy I'd like to avoid if possible – user3953989 Aug 12 at 1:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.