D
D
Dmitry2019-12-09 19:06:36
.NET
Dmitry, 2019-12-09 19:06:36

What's the best algorithm/approach for traversing a tree structure using EntityFramework?

Good day to all. There is the following structure:
5dee6d0b4069d149292317.png
I.e. in this form, the data is stored in the database and the same tree model should come to the user on the UI. Accordingly, the goal is to go through this structure and create a model based on it.
At the moment, this is done as clumsily as possible: a separate mapper has been created for each entity (table), and it all turns out something like this:

var entity = _entityRepository.Table.FirstOrDefault(x => x.Id == id);
var viewModel = _entityBuilder.BuildViewModel(entity);

Inside this builder, the following happens:
var model = new ViewModel();
model.ChildEntitiesA = entity.ChildEntitiesA.Select(childEntityA => childEntityABuilder.BuildViewModel(childEntityA));

///childEntityABuilder
modelChildEntityA.ChildEntitiesB = childEntityA.ChildEntitiesB.Select(childEntityB => childEntityBBuilder.BuildViewModel(childEntityB));

And so on until the end of the entire hierarchy.
As far as I understand, if you remove all the mappers and look at the picture together, you get:
foreach(var childEntityA in entity.childEntitiesA){
 foreach(var childEntityB in childEntityA.ChildEntitiesB){
   foreach(var childEntityC in childEntityB.ChildEntitiesC)
    {
       //..и тд и тп.
    }
}
}

Which, in my opinion, is slightly wrong. It worsens the situation for EF when a separate request is made to the database for each childEntity, because lazy-loading is used. In total, to compile one viewModel to the database, under a hundred (if not more) requests are made. There is a lot of data and it works, well, just sooooooooo slowly.
Actually the question is: is there any beautiful way to bypass this entire hierarchy and minimize the number of iterations / queries?
I would be happy to clarify questions, if any.
Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Korotenko, 2019-12-09
@firedragon

Try this approach
https://entityframework.net/knowledge-base/4853797...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question