Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Include vs Join. Are they equivalent?

Tags:

linq

I have used join in linq to join 2 tables. What is the difference between a join and Include. From what I see, they both behave the same.

    Include vs. Join 
like image 505
Nate Pet Avatar asked Sep 05 '12 15:09

Nate Pet


People also ask

Can we do Joins in LINQ?

In a LINQ query expression, join operations are performed on object collections. Object collections cannot be "joined" in exactly the same way as two relational tables. In LINQ, explicit join clauses are only required when two source sequences are not tied by any relationship.

What does include () do in LINQ?

Introduction to LINQ Include. LINQ include helps out to include the related entities which loaded from the database. It allows retrieving the similar entities to be read from database in a same query. LINQ Include() which point towards similar entities must read from the database to get in a single query.

What type of join is LINQ join?

In LINQ, an inner join is used to serve a result which contains only those elements from the first data source that appears only one time in the second data source. And if an element of the first data source does not have matching elements, then it will not appear in the result data set.

Is LINQ join inner or outer?

One commonly used feature of Language-Integrated Query (LINQ) is the facility to combine two sequences of related data using joins. The standard join operation provides an inner join but with a minor modification can be changed to give a left outer join.


1 Answers

An Included is intended to retain the original object structures and graphs. A Join is needed to project a flattened representation of the object graph or to join types which are not naturally related through the graph (ie. join the customer's city with a shipping facility's city).

Compare the following: db.Customers.Include("Orders") Generates an IEnumerable each of which may contain their corresponding list of Orders in an object graph like this:

Customer 1    Order    Order    Order Customer 2    Order    Order 

In contrast, if you do the same with a join projecting into an anonymous type you could get the following:

    from c in db.Customers      join o in db.Orders on c.CustomerId equals o.CustomerId      select new {c, o} 

This produces a new IEnumerable<Anonymous<Customer, Order>> where the customer is repeated for each order.

{ Customer1, orderA } { Customer1, orderB } { Customer1, orderC } { Customer2, orderD } { Customer2, orderE } { Customer2, orderF } 

While both may issue the same request to the database, the resulting type may be quite different.

like image 155
Jim Wooley Avatar answered Sep 19 '22 19:09

Jim Wooley