Home > Net >  Eager load filter based on child records
Eager load filter based on child records

Time:12-02

public class Parent
{
    public int ParentId { get; set; }
    public IEnumerable<Child> Children { get; set; }
}

public class Child
{
    public int ChildId { get; set; }
    public bool Property { get; set; }
    public Parent Parent { get; set; }
}

How would you eager load the parent class with its child class but filter based on a child class field? For example how would I select Parent records based on whether Child.Property was true? But I would also like to load all the Children of the Parent regardless if their Property property was set to true.

My attempt:

_context.Parents.Include(x => x.Children.Where(x => x.Property == true)).ToListAsync();

This seems to load every parent record, but it loads all the children (regardless of whether their Property property is set to true) of Parents that have a Child with Property property set to true.

CodePudding user response:

How about:

_context.Parents
    .Include(x => x.Children)
    .Where(x => x.Children.Any(c => c.Property))
    .ToListAsync()
  • Related