LINQ to Entities 基於方法的查詢語法

http://msdn.microsoft.com/zh-cn/library/bb399367

實體框架(Entity Framework )是 ADO.NET 中的一套支持開發面向數據的軟件應用程序的技術。

 LINQ to Entities 提供語言集成查詢 (LINQ) 支持,它允許開發人員使用 Visual Basic 或 Visual C# 根據實體框架概念模型編寫查詢。針對實體框架的查詢由針對對象上下文執行的命令目錄樹查詢表示。LINQ to Entities 將語言集成查詢 (LINQ) 查詢轉換爲命令目錄樹查詢,針對實體框架執行這些查詢,並返回可同時由實體框架和 LINQ 使用的對象。

下面列出一些基於方法的查詢語法示例(C#):

投影  Select | SelectMany

篩選 Where | Where…Contains

排序 ThenBy | ThenByDescending

聚合運算符 Average | Count | LongCount | Max | Min | Sum

分區 Skip | Take

轉換 ToArray | ToDictionary | ToList

聯接運算符 GroupJoin | Join

元素運算符 First

分組 GroupBy

導航關係

Select

以下示例使用 Select 方法以將 Product.Name 和 Product.ProductID 屬性投影到一系列匿名類型。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    var query = AWEntities.Products
        .Select(product => new
        {
            ProductId = product.ProductID,
            ProductName = product.Name
        });
 
    Console.WriteLine("Product Info:");
    foreach (var productInfo in query)
    {
        Console.WriteLine("Product Id: {0} Product name: {1} ",
            productInfo.ProductId, productInfo.ProductName);
    }
}

以下示例使用 Select 方法以只返回一系列產品名稱。

1
2
3
4
5
6
7
8
9
10
11
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    IQueryable<string> productNames = AWEntities.Products
        .Select(p => p.Name);
 
    Console.WriteLine("Product Names:");
    foreach (String productName in productNames)
    {
        Console.WriteLine(productName);
    }
}

SelectMany

以下示例使用 SelectMany 方法以選擇 TotalDue 低於 500.00 的所有訂單。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    ObjectSet<Contact> contacts = AWEntities.Contacts;
    ObjectSet<SalesOrderHeader> orders = AWEntities.SalesOrderHeaders;
 
    var query =
    contacts.SelectMany(
        contact => orders.Where(order =>
            (contact.ContactID == order.Contact.ContactID)
                && order.TotalDue < 500.00M)
            .Select(order => new
            {
                ContactID = contact.ContactID,
                LastName = contact.LastName,
                FirstName = contact.FirstName,
                OrderID = order.SalesOrderID,
                Total = order.TotalDue
            }));
 
    foreach (var smallOrder in query)
    {
        Console.WriteLine("Contact ID:{0} Name:{1},{2} Order ID:{3} Total Due: ${4} ",
            smallOrder.ContactID, smallOrder.LastName, smallOrder.FirstName,
            smallOrder.OrderID, smallOrder.Total);
    }
}

以下示例使用 SelectMany 方法以選擇在 2002 年 10 月 1 或此日期之後發出的所有訂單。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    ObjectSet<Contact> contacts = AWEntities.Contacts;
    ObjectSet<SalesOrderHeader> orders = AWEntities.SalesOrderHeaders;
 
    var query =
    contacts.SelectMany(
        contact => orders.Where(order =>
            (contact.ContactID == order.Contact.ContactID)
                && order.OrderDate >= new DateTime(2002, 10, 1))
            .Select(order => new
            {
                ContactID = contact.ContactID,
                LastName = contact.LastName,
                FirstName = contact.FirstName,
                OrderID = order.SalesOrderID,
                OrderDate = order.OrderDate
            }));
 
    foreach (var order in query)
    {
        Console.WriteLine("Contact ID:{0} Name:{1},{2} Order ID:{3} Order date: {4:d} ",
            order.ContactID, order.LastName, order.FirstName,
            order.OrderID, order.OrderDate);
    }
}

Where

以下示例返回所有聯機訂單。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    var onlineOrders = AWEntities.SalesOrderHeaders
        .Where(order => order.OnlineOrderFlag == true)
        .Select(s => new { s.SalesOrderID, s.OrderDate, s.SalesOrderNumber });
 
    foreach (var onlineOrder in onlineOrders)
    {
        Console.WriteLine("Order ID: {0} Order date: {1:d} Order number: {2}",
            onlineOrder.SalesOrderID,
            onlineOrder.OrderDate,
            onlineOrder.SalesOrderNumber);
    }
}

以下示例返回訂單數量大於 2 且小於 6 的訂單。

1
2
3
4
5
6
7
8
9
10
11
12
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    var query = AWEntities.SalesOrderDetails
        .Where(order => order.OrderQty > 2 && order.OrderQty < 6)
        .Select(s => new { s.SalesOrderID, s.OrderQty });
 
    foreach (var order in query)
    {
        Console.WriteLine("Order ID: {0} Order quantity: {1}",
            order.SalesOrderID, order.OrderQty);
    }
}

以下示例返回所有紅色產品。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    var query = AWEntities.Products
        .Where(product => product.Color == "Red")
        .Select(p => new { p.Name, p.ProductNumber, p.ListPrice });
 
    foreach (var product in query)
    {
        Console.WriteLine("Name: {0}", product.Name);
        Console.WriteLine("Product number: {0}", product.ProductNumber);
        Console.WriteLine("List price: ${0}", product.ListPrice);
        Console.WriteLine("");
    }
}

Where…Contains

以下示例將一個數組用作 Where¡Contains 子句的一部分,以查找 ProductModelID 與數組中的值匹配的所有產品。

1
2
3
4
5
6
7
8
9
10
11
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    int?[] productModelIds = { 19, 26, 118 };
    var products = AWEntities.Products.
        Where(p => productModelIds.Contains(p.ProductModelID));
 
    foreach (var product in products)
    {
        Console.WriteLine("{0}: {1}", product.ProductModelID, product.ProductID);
    }
}

作爲 Where¡Contains 子句中謂詞的一部分,您可以使用 ArrayList<(Of <(<'T>)>)> 或實現IEnumerable<(Of <(<'T>)>)> 接口的任何類型的集合。 還可以在 LINQ to Entities 查詢中聲明和初始化集合。

以下示例聲明並初始化 Where¡Contains 子句中的數組,以查找 ProductModelID 或 Size 與數組中的值匹配的所有產品。

1
2
3
4
5
6
7
8
9
10
11
12
13
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    var products = AWEntities.Products.
        Where(p => (new int?[] { 19, 26, 18 }).Contains(p.ProductModelID) || 
                   (new string[] { "L", "XL" }).Contains(p.Size));
 
    foreach (var product in products)
    {
        Console.WriteLine("{0}: {1}, {2}", product.ProductID, 
                                           product.ProductModelID, 
                                           product.Size);
    }
}

ThenBy

採用基於方法的查詢語法的以下示例使用 OrderBy 和 ThenBy 以返回先按姓氏後按名字排序的聯繫人列表。

1
2
3
4
5
6
7
8
9
10
11
12
13
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    IQueryable<Contact> sortedContacts = AWEntities.Contacts
        .OrderBy(c => c.LastName)
        .ThenBy(c => c.FirstName)
        .Select(c => c);
 
    Console.WriteLine("The list of contacts sorted by last name then by first name:");
    foreach (Contact sortedContact in sortedContacts)
    {
        Console.WriteLine(sortedContact.LastName + ", " + sortedContact.FirstName);
    }
}

ThenByDescending

以下示例使用 OrderBy 和 ThenByDescending 方法以首先按標價排序,然後執行產品名稱的降序排序。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    ObjectSet<Product> products = AWEntities.Products;
 
    IOrderedQueryable<Product> query = products
        .OrderBy(product => product.ListPrice)
        .ThenByDescending(product => product.Name);
 
    foreach (Product product in query)
    {
        Console.WriteLine("Product ID: {0} Product Name: {1} List Price {2}",
            product.ProductID,
            product.Name,
            product.ListPrice);
    }
}

Average

以下示例使用 Average 方法來查找產品的平均標價。

1
2
3
4
5
6
7
8
9
10
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    ObjectSet<Product> products = AWEntities.Products;
 
    Decimal averageListPrice =
        products.Average(product => product.ListPrice);
 
    Console.WriteLine("The average list price of all the products is ${0}",
        averageListPrice);
}

以下示例使用 Average 方法以查找每種樣式的產品的平均標價。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    ObjectSet<Product> products = AWEntities.Products;
 
    var query = from product in products
                group product by product.Style into g
                select new
                {
                    Style = g.Key,
                    AverageListPrice =
                        g.Average(product => product.ListPrice)
                };
 
    foreach (var product in query)
    {
        Console.WriteLine("Product style: {0} Average list price: {1}",
            product.Style, product.AverageListPrice);
    }
}

以下示例使用 Average 方法以查找平均應付款總計。

1
2
3
4
5
6
7
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    ObjectSet<SalesOrderHeader> orders = AWEntities.SalesOrderHeaders;
 
    Decimal averageTotalDue = orders.Average(order => order.TotalDue);
    Console.WriteLine("The average TotalDue is {0}.", averageTotalDue);
}

以下示例使用 Average 方法以獲取每個聯繫人 ID 的平均應付款總計。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    ObjectSet<SalesOrderHeader> orders = AWEntities.SalesOrderHeaders;
 
    var query =
        from order in orders
        group order by order.Contact.ContactID into g
        select new
        {
            Category = g.Key,
            averageTotalDue = g.Average(order => order.TotalDue)
        };
 
    foreach (var order in query)
    {
        Console.WriteLine("ContactID = {0} \t Average TotalDue = {1}",
            order.Category, order.averageTotalDue);
    }
}

以下示例使用 Average 方法以針對每個聯繫人獲取具有平均應付款總計的訂單。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    ObjectSet<SalesOrderHeader> orders = AWEntities.SalesOrderHeaders;
 
    var query =
        from order in orders
        group order by order.Contact.ContactID into g
        let averageTotalDue = g.Average(order => order.TotalDue)
        select new
        {
            Category = g.Key,
            CheapestProducts =
                g.Where(order => order.TotalDue == averageTotalDue)
        };
 
    foreach (var orderGroup in query)
    {
        Console.WriteLine("ContactID: {0}", orderGroup.Category);
        foreach (var order in orderGroup.CheapestProducts)
        {
            Console.WriteLine("Average total due for SalesOrderID {1} is: {0}",
                order.TotalDue, order.SalesOrderID);
        }
        Console.Write("\n");
    }
}

Count

以下示例使用 Count 方法以返回 Product 表中的產品數量。

1
2
3
4
5
6
7
8
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    ObjectSet<Product> products = AWEntities.Products;
 
    int numProducts = products.Count();
 
    Console.WriteLine("There are {0} products.", numProducts);
}

以下示例使用 Count 方法以返回聯繫人 ID 的列表和每個聯繫人 ID 所具有的訂單數。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    ObjectSet<Contact> contacts = AWEntities.Contacts;
 
    //Can't find field SalesOrderContact
    var query =
        from contact in contacts
        select new
        {
            CustomerID = contact.ContactID,
            OrderCount = contact.SalesOrderHeaders.Count()
        };
 
    foreach (var contact in query)
    {
        Console.WriteLine("CustomerID = {0} \t OrderCount = {1}",
            contact.CustomerID,
            contact.OrderCount);
    }
}

以下示例按顏色對產品進行分組,並使用 Count 方法以返回每個顏色組中的產品數量。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    ObjectSet<Product> products = AWEntities.Products;
 
    var query =
        from product in products
        group product by product.Color into g
        select new { Color = g.Key, ProductCount = g.Count() };
 
    foreach (var product in query)
    {
        Console.WriteLine("Color = {0} \t ProductCount = {1}",
            product.Color,
            product.ProductCount);
    }
}

LongCount

以下示例以長整型獲取聯繫人計數。

1
2
3
4
5
6
7
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    ObjectSet<Contact> contacts = AWEntities.Contacts;
 
    long numberOfContacts = contacts.LongCount();
    Console.WriteLine("There are {0} Contacts", numberOfContacts);
}

Max

以下示例使用 Max 方法以獲取最大應付款總計。

1
2
3
4
5
6
7
8
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    ObjectSet<SalesOrderHeader> orders = AWEntities.SalesOrderHeaders;
 
    Decimal maxTotalDue = orders.Max(w => w.TotalDue);
    Console.WriteLine("The maximum TotalDue is {0}.",
        maxTotalDue);
}

以下示例使用 Max 方法以獲取每個聯繫人 ID 的最大應付款總計。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    ObjectSet<SalesOrderHeader> orders = AWEntities.SalesOrderHeaders;
 
    var query =
        from order in orders
        group order by order.Contact.ContactID into g
        select new
        {
            Category = g.Key,
            maxTotalDue =
                g.Max(order => order.TotalDue)
        };
 
    foreach (var order in query)
    {
        Console.WriteLine("ContactID = {0} \t Maximum TotalDue = {1}",
            order.Category, order.maxTotalDue);
    }
}

以下示例使用 Max 方法以針對每個聯繫人 ID 獲取具有最大應付款總計的訂單。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    ObjectSet<SalesOrderHeader> orders = AWEntities.SalesOrderHeaders;
 
    var query =
        from order in orders
        group order by order.Contact.ContactID into g
        let maxTotalDue = g.Max(order => order.TotalDue)
        select new
        {
            Category = g.Key,
            CheapestProducts =
                g.Where(order => order.TotalDue == maxTotalDue)
        };
 
    foreach (var orderGroup in query)
    {
        Console.WriteLine("ContactID: {0}", orderGroup.Category);
        foreach (var order in orderGroup.CheapestProducts)
        {
            Console.WriteLine("MaxTotalDue {0} for SalesOrderID {1}: ",
                order.TotalDue,
                order.SalesOrderID);
        }
        Console.Write("\n");
    }
}

Min

以下示例使用 Min 方法以獲取最小應付款總計。

1
2
3
4
5
6
7
8
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    ObjectSet<SalesOrderHeader> orders = AWEntities.SalesOrderHeaders;
 
    Decimal smallestTotalDue = orders.Min(totalDue => totalDue.TotalDue);
    Console.WriteLine("The smallest TotalDue is {0}.",
        smallestTotalDue);
}

以下示例使用 Min 方法以獲取每個聯繫人 ID 的最小應付款總計。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    ObjectSet<SalesOrderHeader> orders = AWEntities.SalesOrderHeaders;
 
    var query =
        from order in orders
        group order by order.Contact.ContactID into g
        select new
        {
            Category = g.Key,
            smallestTotalDue =
                g.Min(order => order.TotalDue)
        };
 
    foreach (var order in query)
    {
        Console.WriteLine("ContactID = {0} \t Minimum TotalDue = {1}",
            order.Category, order.smallestTotalDue);
    }
}

以下示例使用 Min 方法以針對每個聯繫人獲取具有最小應付款總計的訂單。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    ObjectSet<SalesOrderHeader> orders = AWEntities.SalesOrderHeaders;
 
    var query =
        from order in orders
        group order by order.Contact.ContactID into g
        let minTotalDue = g.Min(order => order.TotalDue)
        select new
        {
            Category = g.Key,
            smallestTotalDue =
                g.Where(order => order.TotalDue == minTotalDue)
        };
 
 
    foreach (var orderGroup in query)
    {
        Console.WriteLine("ContactID: {0}", orderGroup.Category);
        foreach (var order in orderGroup.smallestTotalDue)
        {
            Console.WriteLine("Mininum TotalDue {0} for SalesOrderID {1}: ",
                order.TotalDue,
                order.SalesOrderID);
        }
        Console.Write("\n");
    }
}

Sum

以下示例使用 Sum 方法以獲取 SalesOrderDetail 表中訂單數量的總數。

1
2
3
4
5
6
7
8
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    ObjectSet<SalesOrderDetail> orders = AWEntities.SalesOrderDetails;
 
    double totalOrderQty = orders.Sum(o => o.OrderQty);
    Console.WriteLine("There are a total of {0} OrderQty.",
        totalOrderQty);
}

以下示例使用 Sum 方法以獲取每個聯繫人 ID 的應付款總計。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    ObjectSet<SalesOrderHeader> orders = AWEntities.SalesOrderHeaders;
 
    var query =
        from order in orders
        group order by order.Contact.ContactID into g
        select new
        {
            Category = g.Key,
            TotalDue = g.Sum(order => order.TotalDue)
        };
 
    foreach (var order in query)
    {
        Console.WriteLine("ContactID = {0} \t TotalDue sum = {1}",
            order.Category, order.TotalDue);
    }
}

以下示例使用 Skip<(Of <<'(TSource>)>>) 方法以獲取 Contact 表中除前三個聯繫人之外的所有聯繫人。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    // LINQ to Entities only supports Skip on ordered collections.
    IOrderedQueryable<Product> products = AWEntities.Products
            .OrderBy(p => p.ListPrice);
 
    IQueryable<Product> allButFirst3Products = products.Skip(3);
 
    Console.WriteLine("All but first 3 products:");
    foreach (Product product in allButFirst3Products)
    {
        Console.WriteLine("Name: {0} \t ID: {1}",
            product.Name,
            product.ProductID);
    }
}

以下示例使用 Skip<(Of <<'(TSource>)>>) 方法以獲取 Seattle 的前兩個地址之外的所有地址。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    ObjectSet<Address> addresses = AWEntities.Addresses;
    ObjectSet<SalesOrderHeader> orders = AWEntities.SalesOrderHeaders;
 
    //LINQ to Entities only supports Skip on ordered collections.
    var query = (
        from address in addresses
        from order in orders
        where address.AddressID == order.Address.AddressID
             && address.City == "Seattle"
        orderby order.SalesOrderID
        select new
        {
            City = address.City,
            OrderID = order.SalesOrderID,
            OrderDate = order.OrderDate
        }).Skip(2);
 
    Console.WriteLine("All but first 2 orders in Seattle:");
    foreach (var order in query)
    {
        Console.WriteLine("City: {0} Order ID: {1} Total Due: {2:d}",
            order.City, order.OrderID, order.OrderDate);
    }
}

Take

以下示例使用 Take<(Of <<'(TSource>)>>) 方法以只從 Contact 表中獲取前五個聯繫人。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    ObjectSet<Contact> contacts = AWEntities.Contacts;
 
    IQueryable<Contact> first5Contacts = contacts.Take(5);
 
    Console.WriteLine("First 5 contacts:");
    foreach (Contact contact in first5Contacts)
    {
        Console.WriteLine("Title = {0} \t FirstName = {1} \t Lastname = {2}",
            contact.Title,
            contact.FirstName,
            contact.LastName);
    }
}

以下示例使用 Take<(Of <<'(TSource>)>>) 方法以獲取 Seattle 的前三個地址。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    ObjectSet<Address> addresses = AWEntities.Addresses;
    ObjectSet<SalesOrderHeader> orders = AWEntities.SalesOrderHeaders;
 
    var query = (
        from address in addresses
        from order in orders
        where address.AddressID == order.Address.AddressID
             && address.City == "Seattle"
        select new
        {
            City = address.City,
            OrderID = order.SalesOrderID,
            OrderDate = order.OrderDate
        }).Take(3);
    Console.WriteLine("First 3 orders in Seattle:");
    foreach (var order in query)
    {
        Console.WriteLine("City: {0} Order ID: {1} Total Due: {2:d}",
            order.City, order.OrderID, order.OrderDate);
    }
}

ToArray

下面的示例使用 ToArray<(Of <<'(TSource>)>>) 方法立即將序列計算爲數組。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    ObjectSet<Product> products = AWEntities.Products;
 
    Product[] prodArray = (
        from product in products
        orderby product.ListPrice descending
        select product).ToArray();
 
    Console.WriteLine("Every price from highest to lowest:");
    foreach (Product product in prodArray)
    {
        Console.WriteLine(product.ListPrice);
    }
}

ToDictionary

以下示例使用 ToDictionary 方法以立即將序列和相關的鍵表達式轉換爲字典。

1
2
3
4
5
6
7
8
9
10
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    ObjectSet<Product> products = AWEntities.Products;
 
    Dictionary<String, Product> scoreRecordsDict = products.
            ToDictionary(record => record.Name);
 
    Console.WriteLine("Top Tube's ProductID: {0}",
            scoreRecordsDict["Top Tube"].ProductID);
}

ToList

以下示例使用 ToList<(Of <<'(TSource>)>>) 方法以立即將序列轉換爲 List<(Of <(<'T>)>)>,其中,T 屬於類型 DataRow。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    ObjectSet<Product> products = AWEntities.Products;
 
    List<Product> query =
        (from product in products
         orderby product.Name
         select product).ToList();
 
    Console.WriteLine("The product list, ordered by product name:");
    foreach (Product product in query)
    {
        Console.WriteLine(product.Name.ToLower(CultureInfo.InvariantCulture));
    }
}

GroupJoin

以下示例針對 SalesOrderHeader 表和 SalesOrderDetail 表執行 GroupJoin 以查找每個客戶的訂單數。 組聯接等效於左外部聯接,它返回第一個(左側)數據源的每個元素(即使其他數據源中沒有關聯元素)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    ObjectSet<SalesOrderHeader> orders = AWEntities.SalesOrderHeaders;
    ObjectSet<SalesOrderDetail> details = AWEntities.SalesOrderDetails;
 
    var query = orders.GroupJoin(details, 
        order => order.SalesOrderID,
        detail => detail.SalesOrderID,
        (order, orderGroup) => new
        {
            CustomerID = order.SalesOrderID,
            OrderCount = orderGroup.Count()
        });
 
    foreach (var order in query)
    {
        Console.WriteLine("CustomerID: {0}  Orders Count: {1}",
            order.CustomerID,
            order.OrderCount);
    }
 
}

下面的示例對 Contact 和 SalesOrderHeader 表執行 GroupJoin 以查找每個聯繫人的訂單數。 將顯示每個聯繫人的訂單數和 ID。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    ObjectSet<Contact> contacts = AWEntities.Contacts;
    ObjectSet<SalesOrderHeader> orders = AWEntities.SalesOrderHeaders;
 
    var query = contacts.GroupJoin(orders, 
        contact => contact.ContactID,
        order => order.Contact.ContactID,
        (contact, contactGroup) => new
        {
            ContactID = contact.ContactID,
            OrderCount = contactGroup.Count(),
            Orders = contactGroup.Select(order => order)
        });
 
    foreach (var group in query)
    {
        Console.WriteLine("ContactID: {0}", group.ContactID);
        Console.WriteLine("Order count: {0}", group.OrderCount);
        foreach (var orderInfo in group.Orders)
        {
            Console.WriteLine("   Sale ID: {0}", orderInfo.SalesOrderID);
        }
        Console.WriteLine("");
    }
}

Join

以下示例針對 Contact 表和 SalesOrderHeader 表執行聯接。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    ObjectSet<Contact> contacts = AWEntities.Contacts;
    ObjectSet<SalesOrderHeader> orders = AWEntities.SalesOrderHeaders;
 
    var query =
        contacts.Join(
            orders,
            order => order.ContactID,
            contact => contact.Contact.ContactID,
            (contact, order) => new
            {
                ContactID = contact.ContactID,
                SalesOrderID = order.SalesOrderID,
                FirstName = contact.FirstName,
                Lastname = contact.LastName,
                TotalDue = order.TotalDue
            });
 
    foreach (var contact_order in query)
    {
        Console.WriteLine("ContactID: {0} "
                        + "SalesOrderID: {1} "
                        + "FirstName: {2} "
                        + "Lastname: {3} "
                        + "TotalDue: {4}",
            contact_order.ContactID,
            contact_order.SalesOrderID,
            contact_order.FirstName,
            contact_order.Lastname,
            contact_order.TotalDue);
    }
}

以下示例針對 Contact 表和 SalesOrderHeader 表執行聯接,同時按聯繫人 ID 對結果分組。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    ObjectSet<Contact> contacts = AWEntities.Contacts;
    ObjectSet<SalesOrderHeader> orders = AWEntities.SalesOrderHeaders;
 
    var query = contacts.Join(
        orders,
        order => order.ContactID,
        contact => contact.Contact.ContactID,
        (contact, order) => new
        {
            ContactID = contact.ContactID,
            SalesOrderID = order.SalesOrderID,
            FirstName = contact.FirstName,
            Lastname = contact.LastName,
            TotalDue = order.TotalDue
        })
            .GroupBy(record => record.ContactID);
 
    foreach (var group in query)
    {
        foreach (var contact_order in group)
        {
            Console.WriteLine("ContactID: {0} "
                            + "SalesOrderID: {1} "
                            + "FirstName: {2} "
                            + "Lastname: {3} "
                            + "TotalDue: {4}",
                contact_order.ContactID,
                contact_order.SalesOrderID,
                contact_order.FirstName,
                contact_order.Lastname,
                contact_order.TotalDue);
        }
    }
}

First

以下示例使用 First 方法查找以“caroline”開頭的第一個電子郵件地址。

1
2
3
4
5
6
7
8
9
10
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    ObjectSet<Contact> contacts = AWEntities.Contacts;
 
    Contact query = contacts.First(contact =>
        contact.EmailAddress.StartsWith("caroline"));
 
    Console.WriteLine("An email address starting with 'caroline': {0}",
        query.EmailAddress);
}

GroupBy

下面的示例使用 GroupBy 方法來返回按郵政編碼分組的 Address 對象。 這些結果將投影到一個匿名類型。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    var query = AWEntities.Addresses
        .GroupBy( address => address.PostalCode)
        .Select( address => address);                     
 
    foreach (IGrouping<string, Address> addressGroup in query)
    {
        Console.WriteLine("Postal Code: {0}", addressGroup.Key);
        foreach (Address address in addressGroup)
        {
            Console.WriteLine("\t" + address.AddressLine1 +
                address.AddressLine2);
        }
    }
}

下面的示例使用 GroupBy 方法來返回按聯繫人姓氏的首字母分組的 Contact 對象。 這些結果還按姓氏的首字母進行排序,並投影到一個匿名類型。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    var query = AWEntities.Contacts
        .GroupBy(c => c.LastName.Substring(0,1))
        .OrderBy(c => c.Key)
        .Select(c => c);
 
    foreach (IGrouping<string, Contact> group in query)
    {
        Console.WriteLine("Last names that start with the letter '{0}':",
            group.Key);
        foreach (Contact contact in group)
        {
            Console.WriteLine(contact.LastName);
        }
 
    }
}

下面的示例使用 GroupBy 方法來返回按客戶 ID 分組的 SalesOrderHeader 對象。 同時還返回每個客戶的銷售數量。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    var query = AWEntities.SalesOrderHeaders
        .GroupBy(order => order.CustomerID);
 
    foreach (IGrouping<int, SalesOrderHeader> group in query)
    {
        Console.WriteLine("Customer ID: {0}", group.Key);
        Console.WriteLine("Order count: {0}", group.Count());
 
        foreach (SalesOrderHeader sale in group)
        {
            Console.WriteLine("   Sale ID: {0}", sale.SalesOrderID);
        }
        Console.WriteLine("");                    
    }
}

導航關係

實體框架中的導航屬性是快捷方式屬性,用於定位位於關聯各端的實體。導航屬性允許用戶通過關聯集從一個實體導航到另一個實體或從一個實體導航到多個相關的實體。

以下示例採用基於方法的查詢語法,使用 SelectMany 方法以獲取其姓氏爲“Zhou”的聯繫人的所有訂單。 Contact.SalesOrderHeader 導航屬性用於獲取每個聯繫人的 SalesOrderHeader 對象的集合。

1
2
3
4
5
6
7
8
9
10
11
12
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    IQueryable<SalesOrderHeader> ordersQuery = AWEntities.Contacts
        .Where(c => c.LastName == "Zhou")
        .SelectMany(c => c.SalesOrderHeaders);
 
    foreach (var order in ordersQuery)
    {
        Console.WriteLine("Order ID: {0}, Order date: {1}, Total Due: {2}",
            order.SalesOrderID, order.OrderDate, order.TotalDue);
    }
}

採用基於方法的查詢語法的以下示例使用 Select 方法以獲取所有聯繫人 ID 和姓氏爲“Zhou”的每個聯繫人的應付款總計。 Contact.SalesOrderHeader 導航屬性用於獲取每個聯繫人的 SalesOrderHeader 對象的集合。 Sum 方法使用 Contact.SalesOrderHeader 導航屬性以彙總每個聯繫人的所有訂單的應付款總計。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    var ordersQuery = AWEntities.Contacts
        .Where(c => c.LastName == "Zhou")
        .Select(c => new
        {
            ContactID = c.ContactID,
            Total = c.SalesOrderHeaders.Sum(o => o.TotalDue)
        });
 
    foreach (var contact in ordersQuery)
    {
        Console.WriteLine("Contact ID: {0} Orders total: {1}", 
                  contact.ContactID, contact.Total);
    }
}

採用基於方法的查詢語法的以下示例獲取其姓氏爲“Zhou”的聯繫人的所有訂單。 Contact.SalesOrderHeader 導航屬性用於獲取每個聯繫人的 SalesOrderHeader 對象的集合。 聯繫人的姓名和訂單以匿名類型返回。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    var ordersQuery = AWEntities.Contacts
        .Where(c => c.LastName == "Zhou")
        .Select(c => new { LastName = c.LastName, Orders = c.SalesOrderHeaders });
 
    foreach (var order in ordersQuery)
    {
        Console.WriteLine("Name: {0}", order.LastName);
        foreach (SalesOrderHeader orderInfo in order.Orders)
        {
            Console.WriteLine("Order ID: {0}, Order date: {1}, Total Due: {2}",
                orderInfo.SalesOrderID, orderInfo.OrderDate, orderInfo.TotalDue);
        }
        Console.WriteLine("");
    }
}

以下示例使用 SalesOrderHeader.Address 和 SalesOrderHeader.Contact 導航屬性以獲取與每個訂單關聯的 Address 對象和 Contact 對象的集合。 Seattle 城市發生的每個訂單的聯繫人姓氏、街道地址、銷售訂單號和應付款總計將以匿名類型返回。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    var ordersQuery = AWEntities.SalesOrderHeaders
        .Where(o => o.Address.City == "Seattle")
        .Select(o => new
        {
            ContactLastName = o.Contact.LastName,
            ContactFirstName = o.Contact.FirstName,
            StreetAddress = o.Address.AddressLine1,
            OrderNumber = o.SalesOrderNumber,
            TotalDue = o.TotalDue
        });
 
    foreach (var orderInfo in ordersQuery)
    {
        Console.WriteLine("Name: {0}, {1}", orderInfo.ContactLastName, 
                            orderInfo.ContactFirstName);
        Console.WriteLine("Street address: {0}", orderInfo.StreetAddress);
        Console.WriteLine("Order number: {0}", orderInfo.OrderNumber);
        Console.WriteLine("Total Due: {0}", orderInfo.TotalDue);
        Console.WriteLine("");
    }
}

以下示例使用 Where 方法以查找在 2003 年 12 月 1 日之後生成的訂單,然後使用 order.SalesOrderDetail 導航屬性以獲取每個訂單的詳細信息。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    ObjectSet<SalesOrderHeader> orders = AWEntities.SalesOrderHeaders;
 
    IQueryable<SalesOrderHeader> query =
        from order in orders
        where order.OrderDate >= new DateTime(2003, 12, 1)
        select order;
 
 
    Console.WriteLine("Orders that were made after December 1, 2003:");
    foreach (SalesOrderHeader order in query)
    {
        Console.WriteLine("OrderID {0} Order date: {1:d} ",
            order.SalesOrderID, order.OrderDate);
        foreach (SalesOrderDetail orderDetail in order.SalesOrderDetails)
        {
            Console.WriteLine("  Product ID: {0} Unit Price {1}",
                orderDetail.ProductID, orderDetail.UnitPrice);
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章