How to get hierarchy(children or parent's), using LINQ to EF Core

Andrii Shylin 221 Reputation points
2022-08-09T11:35:27.347+00:00

I have a data structure, such as next
class Entity
{
int Id,
int EntityParentId,
string Name
}
And I would like to get all children or parents, could you help me how can I do it with C# LINQ

Developer technologies | .NET | Entity Framework Core
Developer technologies | C#
{count} votes

1 answer

Sort by: Most helpful
  1. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2022-08-09T13:15:07.953+00:00

    If you mean child as a navigation property of a model than try the following extension method.

    public static class DbContexts  
    {  
      
    	public static void GetNavigationDetails(this DbContext context)  
    	{  
    		var modelData = context.Model.GetEntityTypes()  
    			.Select(entityType => new  
    			{  
    				entityType.ClrType.Name,  
    				NavigationProperties = entityType.GetNavigations().Select(x => x.PropertyInfo)  
    			}).ToList();  
      
    		foreach (var item in modelData)  
    		{  
    			Console.WriteLine($"Model name: {item.Name}");  
    			foreach (var info in item.NavigationProperties)  
    			{  
    				Console.WriteLine($"\t{info.Name}");  
    			}  
    		}  
    	}  
    }  
    

    Usage

    using CustomerContext context = new();  
    context.GetNavigationDetails();  
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.