Skip to content

Data.Linq.StandardQueries

Igor Tkachev edited this page May 20, 2016 · 2 revisions

Home / Data / Linq

Select Many (old style join)

from c in db.Category
from p in db.Product
where p.CategoryID == c.CategoryID
select new
{
    c.CategoryName,
    p.ProductName
};

SQL:

SELECT
    [c].[CategoryName],
    [t1].[ProductName]
FROM
    [Categories] [c], [Products] [t1]
WHERE
    [t1].[CategoryID] = [c].[CategoryID]

Inner Join (ANSI join)

from p in db.Product
join c in db.Category on p.CategoryID equals c.CategoryID
select new
{
    c.CategoryName,
    p.ProductName
};

SQL:

SELECT
    [t1].[CategoryName],
    [p].[ProductName]
FROM
    [Products] [p]
        INNER JOIN [Categories] [t1] ON [p].[CategoryID] = [t1].[CategoryID]

Left Join

In the end here we have such clumsy Left Join.

from p in db.Product
join c in db.Category on p.CategoryID equals c.CategoryID into g
from c in g.DefaultIfEmpty()
select new
{
    c.CategoryName,
    p.ProductName
};

SQL:

SELECT
    [t1].[CategoryName],
    [p].[ProductName]
FROM
    [Products] [p]
        LEFT JOIN [Categories] [t1] ON [p].[CategoryID] = [t1].[CategoryID]
Clone this wiki locally