Sign up ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free.

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?

share|improve this question
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. –  Adam Zuckerman Feb 22 '14 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 Feb 22 '14 at 19:51
Take a look at this link… –  Terry Mar 5 '14 at 21:33

1 Answer 1

up vote 3 down vote accepted

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.

share|improve this answer
this is the other way I was thinking, thanks :) –  Deniz Feb 23 '14 at 1:07

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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