Search code examples
c#linqentity-framework-coreincludeirepository

Eager load a single entity


Using Entity Framework and ASP.NET I can easily eagerload a whole list of entities using IRepository.GetAll().Include(). Is there also an easy and short way to eagerload a single entity, like IRepository.Get().Include() ?

For example, I am now writing

var mi = _miRepository.GetAll().Include(m => m.Type).Where(m => m.Id == input.Id).First();

while I feel that getting all and then filtering with Where and First is redundant and ugly. It would look so much cleaner like this:

var mi = _miRepository.Get().Include(m => m.Type);

Solution

  • If your repository pattern is using something like:

    IQueryable<TEntity> GetAll();
    // and 
    TEntity Get(int id);
    

    Then you can alter the Get() method to also return IQueryable:

    IQueryable<TEntity> Get(int id);
    

    where the contents would need to change from something like:

    return _context.DbSet<TEntity>().Find(id);
    

    to:

    return _context.DbSet<TEntity>().Where(x => x.Id == id);
    

    This will mean any existing calls that expected a single entity back will need to be updated from:

    var entity = repository.Get(id);
    

    to:

    var entity = repository.Get(id).Single();
    

    While it may seem counterintuitive to use IQueryable for a method that intends to return a single object, this does give callers the flexibility to leverage projection (.Select()) as well as have control over what related details you might want to eager load, or simply do an exists check (.Any()) without actually loading the entity into memory.