Writing Inner join in LINQ queries

Hi,

I have been playing with LINQ from quite a few days I should say I am impressed with it. It does nearly everything out of box. Yes nearly every thing out of box. And the ORM is also very very powerful. In This post I will illustrate how to use Joins in LINQ queries.

Many a times we want a query where by we retrieve the data from one table and some the related data from the other table. Let says we have a category table and a posts table. Now when I retrieve all the records of the posts I also want to have the related category name (which is there in the category table). So I need to make a join between three tables to get the records. Here is the LINQ Query to do the job.

var t = from p in BlogBLL.Posts

            join cp in BlogBLL.CategoryPosts on p.PostId equals cp.PostId

            join c in BlogBLL.Categories on cp.CategoryID equals c.CategoryID

            select new

            {

                PostId = p.PostId,

                CategoryName = c.CategoryName,

                PostName = p.PostName,

                PostSubName = p.PostSubName           

            };

So basically to make a join between two tables we use the join keyword. After specifying the join keyword we need to provide the column name on which the join will be made.  And then we need to provide the condition on which the join will be made. Hence the on keyword with the condition.

It’s so simple. If you know a little bit of SQL then this syntax should be a cakewalk.

Vikram


Share this post   Email it

Feedback

Posted on 4/10/2009 7:58:47 AM

Thanks for the great (short and to the point) article, it's much appreciated

Posted on 9/15/2009 10:20:51 PM

Nice it is working...

Posted on 9/8/2010 4:54:38 AM

Great article.. short and helpful

Please post your comments:

Name:  
Email (optional): Your email address will not be posted.
URL (optional):
Comments: HTML will be ignored, URLs will be converted to hyperlinks  
Enter the text you see in the box:
 

Copyright © 2006 - 2012 Vikram Lakhotia