| 操作符 | 適用關系 | 關鍵字 | 生成 SQL |
|---|---|---|---|
| SelectMany | 1:N, M:N, 自關聯 | from...from (無 join/into) | CROSS/INNER JOIN |
| Join | 顯式內連接 | join...on...equals | INNER JOIN |
| GroupJoin | 左外連接、分組聚合 | join...into | LEFT JOIN / 子查詢 |
from c in db.Customers
from o in c.Orders // 導航屬性 EntitySet
where c.City == "London"
select o;
from p in db.Products
where p.Supplier.Country == "USA" && p.UnitsInStock == 0
select p; // 生成 LEFT OUTER JOIN Suppliers
from e in db.Employees
from et in e.EmployeeTerritories
where e.City == "Seattle"
select new { e.FirstName, e.LastName, et.Territory.TerritoryDescription };
from e1 in db.Employees
from e2 in e1.Employees
where e1.City == e2.City
select new {
FirstName1 = e1.FirstName, LastName1 = e1.LastName,
FirstName2 = e2.FirstName, LastName2 = e2.LastName,
e1.City
};
from c in db.Customers
join o in db.Orders on c.CustomerID equals o.CustomerID into orders
select new { c.ContactName, OrderCount = orders.Count() };
生成 SQL:子查詢 SELECT COUNT(*) FROM Orders WHERE CustomerID = c.CustomerID。
from c in db.Customers
join o in db.Orders on c.CustomerID equals o.CustomerID into ords
join e in db.Employees on c.City equals e.City into emps
select new { c.ContactName, ords = ords.Count(), emps = emps.Count() };
from e in db.Employees
join o in db.Orders on e.EmployeeID equals o.EmployeeID into ords
from o in ords.DefaultIfEmpty()
select new { e.FirstName, e.LastName, Order = o };
無訂單員工的 Order 為 null。
let z = c.City + c.Country
from o in ords
select new { c.ContactName, o.OrderID, z };
join d in db.OrderDetails
on new { o.OrderID, p.ProductID } equals new { d.OrderID, d.ProductID }
on o.EmployeeID equals (int?)e.EmployeeID
SelectMany (語義清晰)Join/GroupJoinGroupJoin + into 最自然GroupJoin + DefaultIfEmpty()