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?
3
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.
0