Home > OS >  Why does one query return related entities, but not the other?
Why does one query return related entities, but not the other?

Time:04-27

I'm currently migrating existing repositories to a generic one.

The existing method to retrieve a list of all MyEntity from the database looks like:

public IList<MyEntity> GetAll()
{
    var list = _context.MyEntity.Include(_ => _.OtherEntity).ToList();
    return list;
}

This method would return a list of all MyEntity, plus load their related OtherEntites. I've simplified the repository in to a generic one, whose method looks like this:

public IList<TEntity> GetAll(params Expression<Func<TEntity, object>>[] expressions)
        {
            var entity = _context.Set<TEntity>();
            foreach (var expression in expressions)
            {
                entity.Include(expression);
            }
            var list = entity.ToList();
            return list;
        }

And I would call the method like this: var myEntityList = _repository.GetAll(_ => _.OtherEntity);

However this does not seem to load the related OtherEntites. I've had to include the expression parameter for scenarios where loading related entities may or may not be needed.

Could someone explain where I've gone wrong and why my related entities won't load in the new setup? Thanks

CodePudding user response:

It looks like the first method returns the result of .Include() while the second method just calls the method, but ignores the result. LINQ methods usually return a new collection rather than modify the existing collection.

Try this:

public IList<TEntity> GetAll(params Expression<Func<TEntity, object>>[] expressions)
    {
        var entity = _context.Set<TEntity>();
        foreach (var expression in expressions)
        {
            entity = entity.Include(expression);
        }
        var list = entity.ToList();
        return list;
    }
  • Related