Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
259 views
in Technique[技术] by (71.8m points)

LINQ Include vs Join. Are they equivalent?

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
question from:https://stackoverflow.com/questions/12284719/linq-include-vs-join-are-they-equivalent

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...