dimanche 29 mai 2022

Unit of Work implementation on top of EF Core cleanly supporting explicit loading

I have implemented a Repository/Unit of Work on top of EF Core's DbContext:

public interface IUnitOfWork : IDisposable
{
  IUserRepository Users { get; }
  IRoleRepository Roles { get; }
  int Complete();
}

Obviously IUserRepository is a repository of User objects built over the corresponding DbSet:

public interface IRepository<D, E> where D : DbContext where E : class, new()
{
  E Get(long id);
  IEnumerable<E> GetAll();
  IEnumerable<E> Find(Func<E, bool> predicate);
  void Add(E entity);
  void Remove(E entity);
}

public interface IUserRepository : IRepository<MyDbContext, User>
{
  IEnumerable<User> GetCreatedInPeriod(DateTime startDate, DateTime endDate);
  IEnumerable<User> GetInactive();
}

My question is, is there a clean way to support explicit loading through such an implementation? For that, one normally uses the Entry API of DbContext, which is hidden behind the unit of work. One could expose Entry on the unit of work, but then one would be able to write queries starting from a specific entity (have queries leaked out of the unit of work). Since one of my goals is to only expose IEnumerable and not IQueryable (queries leaking), I wanted to ask the above question.

Aucun commentaire:

Enregistrer un commentaire