I want to be able to filter a child collection and only return items in that child collection which match certain conditions. Here's the code that I have now:
var q = from u in context.DbContext.Users select u;
q = q.Include(u => u.UserRoles.Select(ur => ur.Role))
.Where(u=> u.UserRoles.Any(ur=> ur.EnvironmentId == environmentId)
);
My issue with this code is that this is also returning UserRole objects in the UserRole collection that do not match.
For example, if my environmentId
variable has a value of 1, in only want the UserRoles returned in the collection if they have a value of 1 for the EnvironmentId property.
As of right now, it is returning every UserRole regardless of the EnvironmentId value.
Edit
This is not a duplicate question as Gert Arnold has suggested. I do not want to create new or anonymous objects, and the solution i proposed below solves this problem, whereas the article linked to by Gert Arnold does not.