Welcome to MSDN Blogs Sign in | Join | Help

Wriju's BLOG

.NET and everything
LINQ to SQL: Working with hierarchical data

LINQ to SQL supports hierarchical data and you can easily create a query and get output from there. Let us take an example of Northwind database. Northwind has Category -> Products -> Order_Details tables. -> indicates one to many relationships here. So ideally for a Category can have multiple products and a product can have multiple Orders (in Order_Details). Now to get the number of Orders given for each Products under a category of id with their total price we have to write sub queries and SQL will become complex.

 

But if we use LINQ to SQL and drag and drop all the three tables there. The designer will look like,

 

clip_image001

 

Now to get the required output we can write a simple LINQ statement,

 

NorthwindDataContext db = new NorthwindDataContext();

var query =

 

from p in db.Products

where p.CategoryID == 1

select new

{

p.ProductID,

p.ProductName, 

p.Category.CategoryName,

     NumOrders = p.OrderDetails.Count,

     Revenue = p.OrderDetails.Sum(o=>o.UnitPrice * o.Quantity)

};

 

TextBox1.Text = db.GetCommand(query).CommandText;

 

Namoskar!!!

Posted: Saturday, November 10, 2007 2:12 AM by wriju

Comments

Noticias externas said:

LINQ to SQL supports hierarchical data and you can easily create a query and get output from there. Let

# November 9, 2007 9:48 PM

Charlie Calvert's Community Blog said:

Welcome to the thirty-sixth issue of Community Convergence. This is the big day, with Visual Studio 2008

# November 19, 2007 6:13 PM

buzina said:

Where is the hierarchy? I was expecting "real" hierachial data having unfixed depth (e.g. Parent-Child Relationships or more complicated)?

# December 10, 2007 7:00 AM

Dating said:

LINQ to SQL supports hierarchical data and you can easily create a query and get output from there. Let us take an example of Northwind database. Northwind has Category -> Products -> Order_Details tables. -> indicates one to many

# May 31, 2008 2:18 AM

Weddings said:

LINQ to SQL supports hierarchical data and you can easily create a query and get output from there. Let us take an example of Northwind database. Northwind has Category -> Products -> Order_Details tables. -> indicates one to many

# June 5, 2008 9:20 PM
Leave a Comment

(required) 

(required) 

(optional)

(required) 

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Page view tracker