1

I have this linq query which retrieves all element in a database, and filters the output based on some criteria..

I want a list of certain entities, with only attributes that conforms to a specific filter

    var entitiesWithLookupsTolookupEntityName = schemaRepository
        .Many()
        .OrderByDescending(x => x.Version)
        .Take(1)
        .Include(x => x.Entities)
        .ThenInclude(x => x.Attributes)
        .ThenInclude(x => x.AttributeTypeSpecification)
        .SelectMany(x => x.Entities
            .Where(x => x.Attributes.Any(y => y.Type == DataType.Lookup && y.AttributeTypeSpecification.EntityInternalName == lookupEntityName))).AsEnumerable();

This returns the only entity which conforms to the filter, but also includes all the attributes of the entity which does not conform to the filter.

I can though in a second query like this filter them away as such

        var attributefiltered = entitiesWithLookupsTolookupEntityName.SelectMany(x =>
            x.Attributes.Where(y =>
                y.Type == DataType.Lookup && y.AttributeTypeSpecification.EntityInternalName == lookupEntityName));

but why can't I combine both of these?

Seems weird that I am able to do it two steps but not one? Something wrong with using .where() .any()

Pavel Anikhouski
  • 21,776
  • 12
  • 51
  • 66
kafka
  • 573
  • 1
  • 11
  • 28
  • 1
    Does this answer your question? [LINQ - filter child collection](https://stackoverflow.com/questions/8896397/linq-filter-child-collection) – devNull Apr 07 '20 at 22:07
  • It might be in your call to SelectMany. In your first example, SelectMany returned `x => x.Entities.Where`. In your second example, it returned `x => x.Attributes.Where`. Maybe that's the main difference? – Sean Skelly Apr 07 '20 at 22:09
  • @SeanSkelly but how do I apply the `Where` clause on a attribute level and not on entity? – kafka Apr 07 '20 at 22:24
  • Yes, as written you return the Entity matching your filtering (which is based on its Attributes), but it doesn't remove the attributes. What it you filtered the attributes on your first call to .ThenInclude? That call is not filtering which attributes to include. – Sean Skelly Apr 07 '20 at 22:59
  • @SeanSkelly not sure I understand? – kafka Apr 07 '20 at 23:01
  • 1
    `.ThenInclude(x => x.Attributes)` becomes `.ThenInclude(x => x.Attributes.Where( y=> ...` and you add the filtering in the '...' – Sean Skelly Apr 07 '20 at 23:03
  • EntityFramework dont allow filtering in in include... does is this just a pure filter using linq – kafka Apr 07 '20 at 23:05

0 Answers0