C
C#3y ago
Sawaid

Is Recursive Hierarchy LINQ possible without performance hit or multiple DB calls?

Suppose I have a ToDo Entity that has many sub ToDos. Is it possible to get the whole tree structure without any performance hit?
8 Replies
Angius
Angius3y ago
Yep .Include() or, preferably, .Select()
var blogpost = await _ctx.Blogposts
.Where(b => b.Id == id)
.Select(b => new BlogpostDto {
Title = b.Title,
Author = b.Author.UserName,
Tags = b.Tags.Select(t => new TagDto {
Name = t.Name,
Color = t.Color
})
})
.FirstOrDefaultAsync();
var blogpost = await _ctx.Blogposts
.Where(b => b.Id == id)
.Select(b => new BlogpostDto {
Title = b.Title,
Author = b.Author.UserName,
Tags = b.Tags.Select(t => new TagDto {
Name = t.Name,
Color = t.Color
})
})
.FirstOrDefaultAsync();
For example Same goes for recursive Although... with recursive hierarchies you need the .Select() IIRC, using .Include() can lead to some shenanigans
Sawaid
SawaidOP3y ago
By recursive I mean that I get subtasks of subtasks of subtasks of ...
PontiacGTX
PontiacGTX3y ago
you can probably include inner properties if you can loop through them and call Include() ThenInclude() passing an Expression<Func<T,object>>
blinkbat
blinkbat3y ago
the above example from zzzz does this
Sawaid
SawaidOP3y ago
but won't the has a hit on performance?
PontiacGTX
PontiacGTX3y ago
it will in the time it takes to iterate through each property it is will have a time complexity problem the easiest way to to what you want is probably using an expression and apply a select
Sawaid
SawaidOP3y ago
How does a recursive select works?
PontiacGTX
PontiacGTX3y ago
well i am not sure I supose it select those entities within the select clause internally depending on the navigation property and based on the modelBuilder configuration it uses those mapped entities?
Want results from more Discord servers?
Add your server