简体   繁体   中英

The best way to join in Linq

I was working with the first method below, but then I found the second and want to know the difference and which is best.

What is the difference between:

from a in this.dataContext.reglements
join b in this.dataContext.Clients on a.Id_client equals b.Id 
select...

and

from a in this.dataContext.reglements
from b in this.dataContext.Clients
where a.Id_client == b.Id 
select...

I created a test case to test out the difference, and in your scenerio it turns out they are the same.

My test example used AdventureWorks but basically there is an association between

Products->CategoryId->Categories

var q = (
    from p in Products
    from c in Categories
        where p.CategoryID==c.CategoryID
    select p
);

q.ToList();

Produces this SQL:

SELECT [t0].[ProductID], [t0].[ProductName], [t0].[CategoryID]
    FROM [Products] AS [t0], [Categories] AS [t1]
WHERE [t0].[CategoryID] = ([t1].[CategoryID])

var q2 = (
    from p in Products 
    join c in Categories 
        on p.CategoryID equals c.CategoryID
    select p);

q2.ToList();

Produces this sql:

SELECT [t0].[ProductID], [t0].[ProductName], [t0].[CategoryID]
FROM [Products] AS [t0]
INNER JOIN [Categories] AS [t1] ON [t0].[CategoryID] = ([t1].[CategoryID])

The difference between these two syntaxes will be in the way they are translated into SQL. You can trace Entity Framework or LINQ to SQL to determine the SQL:

LINQ to SQL: http://www.reflectionit.nl/Blog/PermaLinkcba15978-c792-44c9-aff2-26dbcc0da81e.aspx

Check the resulting SQL to determine if there are any differences that could affect performance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM