I have heavy query written in another function as expression, by which I can select parent, but how to use this function to select children based on results?
public class Parent
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime Prop1 { get; set; }
public virtual ICollection<Child> Childs { get; set; }
}
public class Child
{
public int Id { get; set; }
public int ParentId { get; set; }
public string Name { get; set; }
public virtual Parent Parent { get; set; }
}
I have function to select parents:
private Expression<Func<Parent, bool>> SelectParents(
DateTime start,
DateTime end,
List<string> names = null
)
{
if (names == null) names = new();
return x => x.Prop1 > start
&& x.Prop1 < end
&& (names.Count > 0 ? names.Contains(x.Name) : true);
}
When I use it to select parents - it works just fine, but how to select children based on this expression?
var parentCount = await _dbContext.Parents.where(SelectParents(.....)).CountAsync();
CodePudding user response:
await _dbContext.Parents
.Where(SelectParents(.....))
.SelectMany(parent => parent.Childs)
.ToListAsync();