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

Andrej 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

Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
697 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,235 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Karen Payne MVP 35,036 Reputation points
    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