Home > Mobile >  Entity Framework Include aren't including related entities
Entity Framework Include aren't including related entities

Time:02-27

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;
    }

CodePudding user response:

I think that you need to change to the following

query =query.Include(property);

CodePudding user response:

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;
    }
  • Related