Linq延遲加載詳細(xì)分析
Linq有很多值得學(xué)習(xí)的地方,這里我們主要介紹Linq延遲加載,包括介紹LoadWith 方法和AssociateWith方法等方面。
Linq延遲加載
在查詢某對(duì)象時(shí),實(shí)際上你只查詢?cè)搶?duì)象。不會(huì)同時(shí)自動(dòng)獲取這個(gè)對(duì)象。這就是Linq延遲加載。
例如,您可能需要查看客戶數(shù)據(jù)和訂單數(shù)據(jù)。你最初不一定需要檢索與每個(gè)客戶有關(guān)的所有訂單數(shù)據(jù)。其優(yōu)點(diǎn)是你可以使用Linq延遲加載將額外信息的檢索操作延遲到你確實(shí)需要檢索它們時(shí)再進(jìn)行。請(qǐng)看下面的示例:檢索出來(lái)CustomerID,就根據(jù)這個(gè)ID查詢出OrderID。
- var custs =
- from c in db.Customers
- where c.City == "Sao Paulo"
- select c;
- //上面的查詢句法不會(huì)導(dǎo)致語(yǔ)句立即執(zhí)行,僅僅是一個(gè)描述性的語(yǔ)句,
- 只有需要的時(shí)候才會(huì)執(zhí)行它
- foreach (var cust in custs)
- {
- foreach (var ord in cust.Orders)
- {
- //同時(shí)查看客戶數(shù)據(jù)和訂單數(shù)據(jù)
- }
- }
語(yǔ)句描述:原始查詢未請(qǐng)求數(shù)據(jù),在所檢索到各個(gè)對(duì)象的鏈接中導(dǎo)航如何能導(dǎo)致觸發(fā)對(duì)數(shù)據(jù)庫(kù)的新查詢。
Linq延遲加載:LoadWith 方法
你如果想要同時(shí)查詢出一些對(duì)象的集合的方法。LINQ to SQL 提供了 DataLoadOptions用于立即加載對(duì)象。方法包括:
LoadWith 方法,用于立即加載與主目標(biāo)相關(guān)的數(shù)據(jù)。
AssociateWith 方法,用于篩選為特定關(guān)系檢索到的對(duì)象。
使用 LoadWith方法指定應(yīng)同時(shí)檢索與主目標(biāo)相關(guān)的哪些數(shù)據(jù)。例如,如果你知道你需要有關(guān)客戶的訂單的信息,則可以使用 LoadWith 來(lái)確保在檢索客戶信息的同時(shí)檢索訂單信息。使用此方法可僅訪問(wèn)一次數(shù)據(jù)庫(kù),但同時(shí)獲取兩組信息。
在下面的示例中,我們通過(guò)設(shè)置DataLoadOptions,來(lái)指示DataContext在加載Customers的同時(shí)把對(duì)應(yīng)的Orders一起加載,在執(zhí)行查詢時(shí)會(huì)檢索位于Sao Paulo的所有 Customers 的所有 Orders。這樣一來(lái),連續(xù)訪問(wèn) Customer 對(duì)象的 Orders 屬性不會(huì)觸發(fā)新的數(shù)據(jù)庫(kù)查詢。在執(zhí)行時(shí)生成的SQL語(yǔ)句使用了左連接。
- NorthwindDataContext db = new NorthwindDataContext();
- DataLoadOptions ds = new DataLoadOptions();
- ds.LoadWith<Customer>(p => p.Orders);
- db.LoadOptions = ds;
- var custs = (
- from c in db2.Customers
- where c.City == "Sao Paulo"
- select c);
- foreach (var cust in custs)
- {
- foreach (var ord in cust.Orders)
- {
- Console.WriteLine("CustomerID {0} has an OrderID {1}.",
- cust.CustomerID,
- ord.OrderID);
- }
- }
語(yǔ)句描述:在原始查詢過(guò)程中使用 LoadWith 請(qǐng)求相關(guān)數(shù)據(jù),以便稍后在檢索到的各個(gè)對(duì)象中導(dǎo)航時(shí)不需要對(duì)數(shù)據(jù)庫(kù)進(jìn)行額外的往返。
Linq延遲加載:AssociateWith方法
使用 AssociateWith 方法指定子查詢以限制檢索的數(shù)據(jù)量。
在下面的示例中,AssociateWith 方法將檢索的 Orders 限制為當(dāng)天尚未裝運(yùn)的那些 Orders。如果沒(méi)有此方法,則會(huì)檢索所有 Orders,即使只需要一個(gè)子集。但是生成SQL語(yǔ)句會(huì)發(fā)現(xiàn)生成了很多SQL語(yǔ)句。
- NorthwindDataContext db2 = new NorthwindDataContext();
- DataLoadOptions ds = new DataLoadOptions();
- ds.AssociateWith<Customer>(
- p => p.Orders.Where(o => o.ShipVia > 1));
- 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, ord.ShipVia,
- //orderDetail.ProductID, orderDetail.Product.ProductName
- }
- }
- }
語(yǔ)句描述:原始查詢未請(qǐng)求數(shù)據(jù),在所檢索到各個(gè)對(duì)象的鏈接中導(dǎo)航如何以觸發(fā)對(duì)數(shù)據(jù)庫(kù)的新查詢而告終。此示例還說(shuō)明在Linq延遲加載關(guān)系對(duì)象時(shí)可以使用 Assoicate With 篩選它們。
【編輯推薦】