Wednesday, 21 December 2011

Joins in LINQ to SQL

The following post shows how to write different types of joins in LINQ to SQL. I am using the My Sample database and LINQ to SQL for these examples


SampleDbDataContext dataContext = new SampleDbDataContext();



Inner Join :-
var q1 = from b in dataContext.Blogs
join c in dataContext.Comments on b.BlogId equals c.BlogId
select new
{
b.BlogId,
b.BlogTitle,
b.BlogDescription,
c.CommentsId,
c.CommentDescription
};
Above LINQ In SQL
SELECT [b].[BlogId], [b].[BlogTitle], [b].[BlogDescription], [c].[CommentsId],[c].[CommentsDescription]
FROM [dbo].[Blogs] AS [b]
INNER JOIN [dbo].[Comments] AS [c] ON [b].[BlogId] = [c].[BlogId]

Left Join :-
var q2 = from b in dataContext.Blogs
join c in dataContext.Comments on b.BlogId equals c.BlogId into g
from s in g.DefaultIfEmpty()
select new
{
b.BlogId,
b.BlogTitle,
b.BlogDescription,
s.CommentsId,
s.CommentDescription
};
Above LINQ In SQL
SELECT [b].[BlogId], [b].[BlogTitle], [b].[BlogDescription], [c].[CommentsId],[c].[CommentsDescription]
FROM [dbo].[Blogs] AS [b]
LEFT OUTER JOIN [dbo].[Comments] AS [c] ON [b].[BlogId] = [c].[BlogId]

No comments:

Post a Comment