Search code examples
entity-frameworklinqincludeeager-loading

Entity Framework Query : Include with where


I want to get all layergroups and include (eager loading) layers that have a specific url.

Here are my tables:

 - LayerGroup (id, List<Layer>layers and more...) 
 - Layer(id, url, List<Attribute>attributes and more...) 
 - Attribute (id and more...)

This is what i got so far.

var groups = _context.LayerGroups
                    .Where(group => group.IsActive)
                    .Where(g => g.Layers.All(l => l.IsActive == true))
                    .Where(g => g.Layers.All(l => l.Url == "example1"))
                    .Include(g => g.Layers)                     
                    .ThenInclude(layer => layer.Attributes)
                    .Include(group => group.Layers).ThenInclude(layer => layer.SearchEngines)
                    .ToList();

But it seems to only get groups if exactly all layers is active and have the url example1. I want to get the layers with the right Url, even if the groups have layers with other url:s.


Solution

  • According to this you cannot filter Include and ThenInclude collection but you can filter parent with the condition based on Include. If you need so then you can write your query as follows:

    var groups = _context.LayerGroups.Where(group => group.IsActive)
                        .Include(g => g.Layers)
                            .ThenInclude(layer => layer.Attributes)
                        .Include(group => group.Layers)
                            .ThenInclude(layer => layer.SearchEngines)
                        .Where(g => g.Layers.Any(l => l.IsActive == true && l => l.Url == "example1"))
                        .ToList();