Nomag
Nomag

Reputation: 43

Entity Framework Include aren't including related entities

I have the following code in my repository. For some reason, query.Include() method does not work and related entity isn't included in result. Double checked if the property name is correctly passed. Maybe I am using it in wrong way? Any Ideas?

public IEnumerable<TEntity> Get(
        Func<TEntity, bool> filter = null,
        Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> order = null,
        string includedProperties = null)
    {
        IQueryable<TEntity> query = _context.Set<TEntity>();

        if (filter is not null)
        {
            query = query.Where(filter).AsQueryable();
        }

        if (order is not null)
        {
            query = order(query);
        }

        if (includedProperties is not null)
        {
            var properties = includedProperties.Split(',', StringSplitOptions.RemoveEmptyEntries);

            foreach (var property in properties)
            {
                query.Include(property);
            }
        }

        return query;
    }

Upvotes: 1

Views: 1116

Answers (2)

Andrew McClement
Andrew McClement

Reputation: 1397

Credit to @Alen.Toma for spotting the missing assignment in the original code.

In the original code, as soon as we use Enumerable.Where(...), the original query on the database can no longer be modified, since we have filtered the objects in C#. This means that query.Include acts on the result of Enumerable.Where, not on the the original db query, and therefore does not have the desired effect.

Full modified code:

public IEnumerable<TEntity> Get(
        Expression<Func<TEntity, bool>> filter = null,
        Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> order = null,
        string includedProperties = null)
    {
        IQueryable<TEntity> query = _context.Set<TEntity>();

        if (filter is not null)
        {
            query = query.Where(filter);
        }

        if (order is not null)
        {
            query = order(query);
        }

        if (includedProperties is not null)
        {
            var properties = includedProperties.Split(',', StringSplitOptions.RemoveEmptyEntries);

            foreach (var property in properties)
            {
                query = query.Include(property);
            }
        }

        return query;
    }

Upvotes: 3

Alen.Toma
Alen.Toma

Reputation: 4870

I think that you need to change to the following

query =query.Include(property);

Upvotes: 2

Related Questions