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 |  digg it! |  reddit! |  bookmark it!

Feedback

Posted on 8/10/2008 12:52:08 AM

You could use foreign keys instead joins) in this case

Posted on 9/17/2008 3:18:55 PM

One catch I discovered is that you can only reference a field from the proceeding join table when doing multiple joins. So with your last line just for example's sake add a category ID to BlogBLL.Posts:

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

Will not work if it references the first table:

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

Strange.

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 - 2008 Vikram Lakhotia