Linq調(diào)用LoadProducts方法
學(xué)習(xí)Linq時(shí),經(jīng)常會(huì)遇到Linq調(diào)用LoadProducts方法問題,這里將介紹Linq調(diào)用LoadProducts方法問題的解決方法。
LoadWith方法和Associate With方法
這個(gè)例子說明:使用LoadWith方法來確保在檢索客戶信息的同時(shí)檢索訂單信息,在檢索訂單信息的同時(shí)檢索訂單詳細(xì)信息, 僅僅訪問一次數(shù)據(jù)庫(kù)。即可以在一個(gè)查詢中檢索許多對(duì)象。使用Associate With方法來限制訂單詳細(xì)信息的排序規(guī)則。
- NorthwindDataContext db2 = new NorthwindDataContext();
- DataLoadOptions ds = new DataLoadOptions();
- ds.LoadWith<Customer>(p => p.Orders);
- ds.LoadWith<Order>(p => p.OrderDetails);
- ds.AssociateWith<Order>(
- p => p.OrderDetails.OrderBy(o => o.Quantity));
- db2.LoadOptions = ds;
- var custs = (
- from c in db2.Customers
- where c.City == "London"
- select c);
- foreach (var cust in custs)
- {
- foreach (var ord in cust.Orders)
- {
- foreach (var orderDetail in ord.OrderDetails)
- {
- //查詢cust.CustomerID, ord.OrderID
- //orderDetail.ProductID, orderDetail.Quantity
- }
- }
- }
語句描述:在原始查詢過程中使用 LoadWith 請(qǐng)求相關(guān)數(shù)據(jù),以便稍后在檢索到的各個(gè)對(duì)象中導(dǎo)航時(shí)此示例還說明在急切加載關(guān)系對(duì)象時(shí)可以使用 Assoicate With 對(duì)它們進(jìn)行排序。
Linq調(diào)用LoadProducts方法
這個(gè)例子在Category類里提供了一個(gè)LoadProducts分部方法。當(dāng)產(chǎn)品的類別被加載的時(shí)候,就直接優(yōu)先Linq調(diào)用LoadProducts方法來查詢沒有貨源的產(chǎn)品。
- private IEnumerable<Product> LoadProducts(Category category)
- {
- //在執(zhí)行LINQ to SQL的時(shí)候,這個(gè)LoadProducts分部方法
- //優(yōu)先加載執(zhí)行,這里用存儲(chǔ)過程也可以.
- return this.Products
- .Where(p => p.CategoryID == category.CategoryID)
- .Where(p => !p.Discontinued);
- }
執(zhí)行下面的查詢時(shí),利用上面方法返回的數(shù)據(jù)進(jìn)行下面的操作:
- NorthwindDataContext db2 = new NorthwindDataContext();
- DataLoadOptions ds = new DataLoadOptions();
- ds.LoadWith<Category>(p => p.Products);
- db2.LoadOptions = ds;
- var q = (
- from c in db2.Categories
- where c.CategoryID < 3
- select c);
- foreach (var cat in q)
- {
- foreach (var prod in cat.Products)
- {
- //查詢cat.CategoryID, prod.ProductID
- }
- }
語句描述:重寫 Category 類中的分部方法LoadProducts。加載某種類別的產(chǎn)品時(shí),Linq調(diào)用LoadProducts方法以加載此類別中未停產(chǎn)的產(chǎn)品。
【編輯推薦】