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