2013-10-14 55 views
0

如何提高以下linq查詢的性能?如何提高此LINQ查詢的性能?

運行它時,它拋出了一個錯誤System.OutOfMemoryException注:我在XrmContext.sun_POSSet實體

var a = (from temple in XrmContext.sun_POSSet 
     select new POS() 
     { 
      id = temple.Id, 
      Country = temple.sun_sun_country_sun_POS == null ? "" : temple.sun_sun_country_sun_POS.sun_name, 
      CountryId = temple.sun_sun_country_sun_POS == null ? "" : temple.sun_sun_country_sun_POS.Id.ToString(), 
      stringint = temple.sun_sun_stringint_sun_placeofstu == null ? "" : temple.sun_sun_stringint_sun_placeofstu.sun_name, 
      stringintId = temple.sun_sun_stringint_sun_placeofstu == null ? "" : temple.sun_sun_stringint_sun_placeofstu.Id.ToString(), 
      FullName = temple.sun_contact_sun_POS.FullName, 
      EMail = temple.sun_contact_sun_POS.EMailAddress1, 
      MobilePhone = temple.sun_contact_sun_POS.MobilePhone 
     }).ToList<POS>(); 
+1

如果你在這個表中有很多記錄,你是否真的需要把它們全部拉回來?也許增加一個where子句只提取相關記錄? –

+1

這是'IQueryable'存在的原因之一。在調用'ToList()'之前,'IQueryable'存儲查詢以及如何處理結果,但實際上並沒有處理它們。使用Skip()和Take()可以取出你實際需要的記錄。如果你需要處理它們,可以批量處理(比如說)500 – Basic

+0

你也可以使用IEnumerable,然後你可以逐一處理每個項目。理解這一點非常重要,當你這樣做時,任何流的「倒回」都是非常不起作用的。這是許多人建議你爲每個Linq查詢添加'.ToList()'的常見原因。 – Aron

回答

3

有很多記錄沒有關於記錄數量的更多信息,我會說你要的OutOfMemoryException,因爲你是在一個數據集是調用ToList()太大而無法保存在記憶中。

ToList()強制對底層IQueryable<T>進行評估,在這種情況下會導致所有記錄返回到客戶端並在內存中實例化。在你的情況下,根本沒有足夠的空間 - 你不應該假設會有。 當您將數據集帶回客戶端時,使數據集變小。

您應該考慮使用Skip()Take()來實現分頁,或使用適當的Where()子句來過濾數據。

+0

我有100502條記錄 –