LINQ包含与加入.它们相等吗? [英] LINQ Include vs Join. Are they equivalent?

查看:63
本文介绍了LINQ包含与加入.它们相等吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在linq中使用join来联接2个表.联接和包含之间有什么区别.从我的角度来看,它们的行为相同.

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

推荐答案

包含"旨在保留原始对象结构和图形.需要使用Join来投影对象图的展平表示或通过该图自然不相关的联接类型(即,将客户所在的城市与运输工具所在的城市联接在一起).

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).

比较以下内容: db.Customers.Include("Orders") 生成这样的对象图:

Compare the following: db.Customers.Include("Orders") Generates an object graph like this:

Customer
   Order
   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}

// produces new Anonymous<Customer, Order> 

虽然两者都可能向数据库发出相同的请求,但结果类型可能会完全不同.

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

这篇关于LINQ包含与加入.它们相等吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆