Home > Net >  Filter the list based on a list inside
Filter the list based on a list inside

Time:01-09

I have this models

public class ModelA {
    public int Id { get; set; }
    public string Name { get; set; }

    public List<ModelB> ModelBClass { get; set; }
}

public class ModelB {
    public int Id { get; set; }
    public int ModelAId { get; set; }
    public ModelA modelA { get; set; }
    public bool IsActive { get; set; }
}

And I'm using the below LINQ to filter that will show all ModelA with a ModelB IsActive status = true

_dbContext.ModelA.Include(c=>c.ModelBClass.Where(d=>d.IsActive == true)).ToListAsync();

But I'm getting an error: "Lambda expression used inside Include is not valid

Tried other things to filter but doesn't help. I want to show all ModelA with all the IsActive: true for all ModelB class.

CodePudding user response:

I do not believe you want a filtered include, which does not filter the outer collection. Instead you want a .Where( ... .Any(...)) condition that essentially does the equivalent of a SQL WHERE EXISTS(...).

Try something like:

_dbContext.ModelA
    .Include(a = a.ModelBClass)
    .Where(a => a.ModelBClass.Any(b => b.IsActive))
    .ToListAsync();

The include might not be needed. You can try both with and without.

CodePudding user response:

You can show all ModelA with all the IsActive: true for all ModelB class using Where to filter a sequence of values and All() to determine whether element of a sequence satisfy a condition:

_dbContext.ModelA.Where(c => c.ModelBClass.All(d => d.IsActive)).ToListAsync();
  • Related