2012-03-06 91 views
2

好日子,System.Linq.Select方法錯誤:LINQ到實體無法識別方法

我的代碼生成運行時錯誤,我不知道如何解決這個問題。任何幫助,將不勝感激。

我們的代碼是經過「報價」列表調用下面的第二個轉換方法。報價是來自EDMX模型的一個對象。第一個Convert方法接受對象並將其轉換爲DTO類,然後返回。

運行程序時,我遇到以下錯誤:

LINQ to Entities does not recognize the method '...Domain.Holdings.OfferDto Convert(...Repository.Offer, System.Nullable`1[System.Int32])' method, and this method cannot be translated into a store expression.

的代碼如下:

public class OfferDtoMapping 
{ 
    public static OfferDto Convert(Offer offer, int? participantId) 
    { 
     if (offer == null) 
      throw new ArgumentException("The Offer object supplied for conversion cannot be null"); 

     var unitCost = offer.UnitCost; 
     if (offer.Trust.Company.AllowInterDiv && participantId.HasValue) 
     { 
      Assign another value to unitCost... 
     } 

     var output = new OfferDto 
     {    
      Assign the offer properties to the OfferDto properties... 
     }; 
     return output;   
    } 

    public static IList<OfferDto> Convert(IQueryable<Offer> offerList) 
    { 
     return offerList == null ? new List<OfferDto>() : offerList.Select(ol => Convert(ol, null)).ToList(); 
    } 
} 

在此行中出現的錯誤:

return offerList == null ? new List<OfferDto>() : offerList.Select(ol => Convert(ol, null)).ToList(); 

我懷疑這個錯誤與我通過採用2個inp的方法投影offerList的事實有關ut參數。我們嘗試傳遞0而不是NULL(因爲我們最初認爲這是問題),但仍然收到類似的錯誤消息。

爲了保持整個我們的解決方案的一致性,我們要使用選擇方法,而不是用foreach語句代替這種方式來保持。

在我們目前的情況下有沒有使用Select方法的方法?

預先感謝您。

回答

2

的錯誤,因爲沒有在LINQ到實體轉換方法沒有transaltion。您需要首先通過調用Iqueryable數據上的ToList()來強制評估數據。轉換可以在Linq之外執行到內存中的Entites。

return offerList == null ? new List<OfferDto>() : offerList.ToList().Select(ol => Convert(ol, null)).ToList(); 
+0

非常好,謝謝你,謝謝大家這樣快速的回答。我測試了它,它工作。 – Matei 2012-03-06 12:07:56

+0

作爲'ToList()'的替代方法,可以使用'AsEnumerable()',這可能更有效,因爲它不需要分配兩次列表。 – svick 2012-03-06 12:34:08

2

LINQ到實體試圖您Select語句轉換成基礎數據庫的有效表達。由於您無法瞭解您的Convert方法,因此此翻譯將失敗,從而導致您看到的錯誤。

到對象處理Select語句可以解決,通過讓Linq的。

offerList.ToList().Select(ol => Convert(ol, null)); 
2

您不能調用從linq2entities方法,您可以在linq2object做到這一點,所以第一次提取數據,然後調用方法:

return offerList == null ? new List<OfferDto>() : offerList.ToList() 
                .Select(ol => Convert(ol, null)) 
                .ToList() 

offerList.ToList()去抓取來自DB數據到內存中,然後你可以簡單地在其上運行linq2object方法。事實上,一些預定義的系統方法可以從linq2entity調用,並且不允許用戶定義的方法(因爲linq2sql不能創建表達式樹)。發生

相關問題