I have a ef class model - entity for "Resource" which has many properties around 130. This class "Resource" has a property called "ParentId", so basically a Resouce can have child or can have no child - which is linked to the same entity by key called "ParentId"
I have a db table , and its entity looks in ef as attached in image
I want to write a Linq query to get all parent and childrens with the attached format as in image
Can you help me how can i achive this in by querying in ef.



Tahir AnsariRank #366 · 6.8K reputationPosted Oct 13, 2023, 6:02 AM EDT
using (var context = new YourDbContext()) { // Query for top-level parents and their children var resources = context.Resources .Include(r => r.Children) // Eager load children .Where(r => r.ParentId == null) .ToList(); foreach (var resource in resources) { Console.WriteLine($"Parent: {resource.Name}"); foreach (var child in resource.Children) { Console.WriteLine($"- Child: {child.Name}"); } } }