This ASP .NET MVC application implements Entity Framework.

I've declared the repositories in the DbContext like this:

public class CompanyDbContext : DbContext
        // constructor goes here

        public DbSet<Customer> Customers { get; set; }
        public DbSet<Order> Orders { get; set; }
        public DbSet<CustomerOrder> CustomerOrders { get; set; }

        private IGeneralEntityRepository<Customer> customersRepository;
        private IGeneralEntityRepository<Order> ordersRepository;

        // ...................

This way we can declare and initialise CompanyDbContext within a controller and then access the repositories using the CompanyDbContext instance.

Is this correct? Or should I create a separate "Unit Of Work" class to access the repositories?

  • This is the way EF5 builds out your code. And the controller builder puts private CompanyDbContext db = new CompanyDbContext(); this in each controller it builds. Commented Feb 22, 2014 at 2:54
  • I understand that this is the way that EF implements the repository pattern. My question is, is this the right way to merge my own repositories with the EF repository? Thanks :)
    – Deniz
    Commented Feb 22, 2014 at 19:51
  • Take a look at this link blog.longle.net/2013/05/11/… Commented Mar 5, 2014 at 21:33

1 Answer 1


Your repositories need to depend on the DbContext and not vice versa. Also, you don't have to implement Unit of Work since the DbContext already implements it. You could do it like this:

public interface IRepository<T>
    T ReadOne(object key);

    // so on, so forth...

public class Repository<T> : IRepository<T> where T : class, new()
    public Repository(DbContext context)
        _context = context;

    private readonly DbContext _context;

    public T ReadOne(object key)
        return _context.Set<T>().Find(key);

This way, you keep your context clean and only need to worry about adding new entity configurations to it, when it is needed. If you use EF6 there's a method called AddFromAssembly which allows you to add the configurations from an assembly. This saves you from modifying the DbContext each time you add a new entity.

I'd suggest looking into a DI container as it will greatly simplify the work required to put things together. You can sort out your DAL configuration with 2 or 3 lines of code.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.