0

I'm struggling to find a way to use Include() with some kind of Where condition with passed in lambda expression.

It will be something like this:

Sample usage: userRepository.Get(id, isActive: true, u=>u.UserRoles, u=>u.Group)

public T Get(long id, bool? isActive = true, params Expression<Func<T, object>>[] includes)
    {
        // Sample usage
        // userRepository.Get(id, true, u=>u.UserRoles, u=>u.Group)

        IQueryable<T> query = DataContext.Set<T>().Where(_ =>
            _.Id == id && (!isActive.HasValue || isActive.Value == _.IsActive));

        return
            includes.Aggregate(query, (current, includeProperty) => current.Include(includeProperty))
                .FirstOrDefault();
    }
}

Problem:

All userRoles and group with IsActive = false are included in the result set.

Expectation:

I want to find a way to use Include with Where condition. So it will like this:

userRepository.Get(id, true, u=>u.UserRoles.Where(ur => ur.IsActive == true, u=>u.Group)

I already tried to search in the stack.

Community
  • 1
  • 1
Vu Nguyen
  • 3,605
  • 3
  • 22
  • 34
  • This looks very similar to http://stackoverflow.com/questions/8333934/entity-framework-selective-condition-on-included-navigation-property?rq=1 or possibly this one: http://stackoverflow.com/questions/14271475/conditional-include-not-working-with-entityt-framework-5?rq=1 – Eris Nov 29 '14 at 09:16
  • 1
    It is not possible to filter in the Include()-Method. See [this workitem](https://entityframework.codeplex.com/workitem/47). In the comments are some links to alternative solutions, f.e. use projection to an anonymous type. – user3411327 Nov 29 '14 at 09:26

0 Answers0