I need to filter the elements and their child elements to display on the list, the idea was to search on the parent or child elements that contains the text to search, so I first launch the query with Include().
Then manipulate the result with the Where function on the parent and child elements.
But the EntityFramework had some strange results, the 1st time all went well, but when I wanted to do another EntityFramework search returned the parent elements with 0 child elements
Here’s a simplified example:
{
"Project Test A":[
{
"Project.Child A.1",
"Project.Child A.2"
}
],
"Project Test B"[
{
"Project.Child B.1",
"Project.Child B.2"
}
],
"Test C":[
{
"Test.Child C.1",
"Test.Child C.2"
}
],
"Test D":[
{
"Test.Child D.1",
"Test.Child D.2"
}
]
}
Now, if I launch the 1st search with text “Project”, the result seem correct:
[
"Project Test A":[
{
"Project.Child A.1",
"Project.Child A.2"
}
],
"Project Test B"[
{
"Project.Child B.1",
"Project.Child B.2"
}
]
But now if I launch the 2nd search with text “Test”, this is what I get:
{
"Project Test A":[
{
"Project.Child A.1",
"Project.Child A.2"
}
],
"Project Test B"[
{
"Project.Child B.1",
"Project.Child B.2"
}
],
"Test C":[
{
}
],
"Test D":[
{
}
]
}
and this is the search function:
public async Task<IEnumerable<Parent>> GetProjectAsync(string? search)
{
Task<List<Parent>> enumParentAsync = _context.Parent
.Include(p => p.Child).ToListAsync();
List<Parent> enumParent = await enumParentAsync;
if(search != null)
{
//Firest child level
foreach(Parent proj in enumParent)
{
proj.Child = proj.Child.Where(c => c.label.ToLower().Contains(search.ToLower())).ToList();
}
//Then parent level
return enumParent.Where(p => p.Child.Count > 0 || p.label.ToLower().Contains(search.ToLower())).ToList();
}
return enumParent.ToArray();
}