2011-06-17 15 views
1

我不知道如何解決這個LINQ to SQL問題,我有。我的對象圖中的一個子對象的屬性沒有像我所預期的那樣加載。Linq - 在子對象上加載EntitySet/EntityRef - 只有1級可加載?

我的數據訪問代碼封裝在模型層中,因此在返回對象之前需要完成完整對象圖的加載。

我使用下面的代碼來填充對象圖。

「發票」是此處的目標對象。它有一個父對象「Order」和子對象「InvoiceItems」。

除了「OrderItems」,它們是「Order」的直接子元素,但也映射到「InvoiceItems」的所有內容都加載在這裏。它們通過參考本文中的「InvoiceItems」來訪問。

這顯然是因爲「OrderItems」離開「Invoice」對象的兩個級別,通過Invoice.InvoiceItems.OrderItem訪問,其中載入選項中指定的其他屬性直接映射到發票。

如何加載對象遠離目標對象2個等級?

我希望這是有道理的。

using (var dc = new ProjDataContext(Config.ConnectionStringERPDB)) 
      { 
       if (loadObjectGraph) 
       { 
        var loadOptions = new DataLoadOptions(); 

        loadOptions.LoadWith<Invoice>(x => x.InvoiceItem); 
        loadOptions.LoadWith<Invoice>(x => x.Order); 
        loadOptions.LoadWith<InvoiceItem>(x => x.OrderItem); 
        loadOptions.LoadWith<OrderItem>(x => x.Product); 

        dc.LoadOptions = loadOptions; 
       } 

       Invoice invoice = (from c in dc.Invoice 
            where c.ID == invoiceID 
            select c).FirstOrDefault(); 

       return invoice; 
      } 

回答

2

看來您無法從我找到的其他信息中加載多個關卡。

我已經添加了一段非常髒的額外代碼來填充我需要訪問的屬性。

這可能不是一個很好的解決方案 - 歡迎任何輸入!

//預先加載abover只適用於一個水平

  // http://stackoverflow.com/questions/1191331/using-linq-to-sql-how-do-i-eager-load-all-child-and-any-nested-children-results 
      // http://www.lowendahl.net/showShout.aspx?id=190 

      if (loadObjectGraph) 
      { 
       foreach (InvoiceItem invoiceItem in invoice.InvoiceItem) 
       { 
        var ii = invoiceItem; 

        OrderItem oiList = (from oi in dc.OrderItem 
             where oi.ID == ii.OrderItemID 
             select oi).FirstOrDefault(); 

        invoiceItem.OrderItem = oiList; 
       } 
      } 
+0

這是奇怪的。您可以使用EF進行深度加載,但我不知道您無法使用L2S進行加載。很高興知道。 – 2011-06-17 14:23:46