首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

LINQ to SQL Join 與 Order By 完整指南(6):內部聯結、SelectMany 一對多導覽、GroupJoin 分組聯結實戰

     編輯:關於ASP.NET

掌握 LINQ to SQL 多表查詢的三大模式:Join、SelectMany、GroupJoin,對應不同關聯關係。

1. Join:內部聯結(一對一、多對一)


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。

2. SelectMany:一對多導覽(無需 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 };

3. GroupJoin:分組聯結(左外部聯結 + 分組)


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。

Order By 排序


var q = from p in db.Products
        orderby p.CategoryID, p.UnitPrice descending
        select p;

支援 ascending/descending、多欄位、複合運算式排序。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved