0

I want to perform left join using two or more table in Linq to Sql query but it looks like there is no keyword for doing so in C#. Is there any way to perform left join in the same way we do inner joins using Linq to Sql?

public IQueryable GetProducts(int productID)
{
    var products = 
        from p in this.Products 
        left join c in this.ProductCategoryProducts 
        on p.CategoryID equals c.ProductCategoryID
        left join ac in this.ProductCategories 
        on c.ProductCategoryID equals ac.ProductCategoryID
        where p.ProductID == productID
        select new
        {
            ProductID = a.ProductID,
            Heading = p.Heading,                
            Category = ac.ProductCategory
        };
    return products ;
}
Sonu K
  • 2,562
  • 2
  • 20
  • 32
  • 1
    `DefaultIfEmpty()` is the trick to left outer joins in Linq. See this http://msdn.microsoft.com/en-us/library/bb397895.aspx – Ben Robinson Sep 19 '14 at 13:31
  • check this answer for a good explanation of group join http://stackoverflow.com/a/15599143/2617732 – rdans Sep 21 '14 at 10:53

2 Answers2

0
public IQueryable GetProducts(int productID)
{
    var products = 
        from p in this.Products 
        join c in this.ProductCategoryProducts 
        on p.CategoryID equals c.ProductCategoryID into pclj
        from pc in pclj.DefaultIfEmpty()
        join ac in this.ProductCategories 
        on c.ProductCategoryID equals ac.ProductCategoryID into pcidlj
        from pcid in pcidlj.DefaultIfEmpty()
        where p.ProductID == productID
        select new
        {
            ProductID = p.ProductID,
            Heading = p.Heading,                
            Category = pcid != null ? pcid.ProductCategory : null
        };
    return products ;
}
0

Anyways I got the solution using Lambda expressions in this way:

var products = 
        from p in this.Products 
        join cat in this.ProductCategoryProducts 
        .Where(c => c.ProductID == p.ProductID).DefaultIfEmpty()

        from pc in this.ProductCategories 
        .Where(pc => pc.ProductCategoryID == cat.ProductCategoryID).DefaultIfEmpty()

        where p.ProductID == productID
        select new
        {
            ProductID = p.ProductID,
            Heading = p.Heading,                
            Category = pc.ProductCategory
        };
    return products ;
Sonu K
  • 2,562
  • 2
  • 20
  • 32