'C# Entity Framework Core how to add nested ThenInclude for User -> Manage relation
I have an entity called User and it has a navigation property Manager' which refers to a User entity.
public class User
{
public virtual User Manager { get; set; }
}
return await _context.User
.AsNoTracking()
.Include(user => user.Manager)
.ThenInclude(manager => manager.Manager)
private int? FindUser(int tagId, User user)
{
if (user.Manager == null)
{
Log.Error($"Cannot find User");
return null;
}
if (!user.Manager.UserTag.Any(x => !x.Disabled && x.TagId == tagId))
{
return FindExCoUser(tagId, user.Manager);
}
}
My requirement is for some cases I had to go up in the hierarchy of user managers'. In the above query I get only the current user and his manager but if I had to go up in the hierarchy, the manager is returned as null.
Do I need to keep adding .ThenInclude but how many times?
Or is there a better solution to achieve this?
Thanks
Solution 1:[1]
You can recursively select your managers. Here is an example I found on the Internet: https://michaelceber.medium.com/implementing-a-recursive-projection-query-in-c-and-entity-framework-core-240945122be6
But if you want to select all managers, your exit condition must be user.Manager == null instead of a max depth.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Lukas Hein |
