Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving a tree structure from a database using LINQ

I have an organization chart tree structure stored in a database. Is is something like

ID (int);
Name (String);
ParentID (int)

In C# it is represented by a class like

class Employee
{
int ID, 
string Name, 
IList < Employee> Subs
} 

I am wondering how is the best way to retrieve these values from the database to fill up the C# Objects using LINQ (I am using Entity Framework)

There must be something better than making a call to get the top level then making repeated calls to get subs and so on.

How best to do it?

like image 705
Emad Gabriel Avatar asked Jan 06 '10 19:01

Emad Gabriel


People also ask

Is LINQ to SQL obsolete?

LINQ to SQL was the first object-relational mapping technology released by Microsoft. It works well in basic scenarios and continues to be supported in Visual Studio, but it's no longer under active development.

What is returned from a LINQ query?

By default, LINQ queries return a list of objects as an anonymous type. You can also specify that a query return a list of a specific type by using the Select clause.

What is any () in LINQ?

The Any operator is used to check whether any element in the sequence or collection satisfy the given condition. If one or more element satisfies the given condition, then it will return true. If any element does not satisfy the given condition, then it will return false.


1 Answers

  1. You can build a stored proc that has built in recursion. Take a look at http://msdn.microsoft.com/en-us/library/ms190766.aspx for more info on Common Table Expressions in SQL Server
  2. You might want to find a different (better?) way to model your data. http://www.sqlteam.com/article/more-trees-hierarchies-in-sql lists a popular way of modeling hierarchical data in a database. Changing the modeling can allow you to create queries that can be expressed without recursion.
like image 137
hackerhasid Avatar answered Oct 25 '22 01:10

hackerhasid