掌握 LINQ to SQL 多表查詢的三大模式:Join、SelectMany、GroupJoin,對應不同關聯關係。
var q = from c in db.Customers
join o in db.Orders on c.CustomerID equals o.CustomerID
select new { c.ContactName, o.OrderDate };
等同 SQL INNER JOIN。
條件:查詢無 join/into,且來源為 EntitySet 導覽屬性。
var q = from c in db.Customers
from o in c.Orders // 導覽屬性 EntitySet
where c.City == "London"
select o;
var q = from p in db.Products
where p.Supplier.Country == "USA" && p.UnitsInStock == 0
select p;
生成 LEFT OUTER JOIN Suppliers,自動處理供應商可能為 Null。
var q = from e in db.Employees
from et in e.EmployeeTerritories
where e.City == "Seattle"
select new { e.FirstName, e.LastName, et.Territory.TerritoryDescription };
var q = from c in db.Customers
join o in db.Orders on c.CustomerID equals o.CustomerID into g
select new { c.ContactName, OrderCount = g.Count() };
等同 SQL LEFT JOIN ... GROUP BY,無訂單客戶 OrderCount 為 0。
var q = from p in db.Products
orderby p.CategoryID, p.UnitPrice descending
select p;
支援 ascending/descending、多欄位、複合運算式排序。