Writing Inner join in LINQ queries
Posted on 8/25/2007 8:02:08 AM
in #Asp.Net 3.X
Hi,/P>
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./P>
var t = from p in BlogBLL.Posts /P>
/SPAN>join cp in BlogBLL.CategoryPosts on p.PostId equals cp.PostId/P>
/SPAN>join c in BlogBLL.Categories on cp.CategoryID equals c.CategoryID/P>
/SPAN>select new /P>
/SPAN>{/P>
/SPAN> /SPAN>PostId = p.PostId,/P>
/SPAN>CategoryName = c.CategoryName,/P>
/SPAN>PostName = p.PostName,/P>
/SPAN>PostSubName = p.PostSubName /SPAN>/P>
/SPAN>};/P>
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. /SPAN>And then we need to provide the condition on which the join will be made. Hence the on keyword with the condition./P>
It’s so simple. If you know a little bit of SQL then this syntax should be a cakewalk./P>
Vikram/P>
|
Posted on 4/10/2009 7:58:47 AM
Thanks for the great (short and to the point) article, it's much appreciated
/p>
|
Posted on 9/15/2009 10:20:51 PM
Nice it is working...
/p>
|
Posted on 9/8/2010 4:54:38 AM
Great article.. short and helpful
/p>
|