Linq Querys and Joins
March 31st, 2008
I have been playing with LINQ just a few times but I can say I am impressed with it. It does nearly everything out of box. 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 Blog.Posts join cp in Blog.CategoryPosts on p.PostId equals cp.PostId join c in Blog.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 shouldn’t be a problem. LINQ makes working with data in its various guises easier.
By intergating it into the language, we have rich integrated support for working with data.
However, there are times where the syntax is slighly different from what you would typically expect with TSQL. Once case where this occurs is when trying to join two data sources that are related by more than one field (also know as a composite key). This differs from standard joins where one table has a primary key and the other table has a foreign key id.





