2011-03-11 40 views
2

我無法理解爲什麼在下面的代碼中出現錯誤。我確信我缺少一些簡單的東西,但我需要幫助理解。Linq。使用LinqPad選擇方法問題

我一直在使用LinqPad運行LinqToSql此代碼。

我在LinqPad以下代碼:

有三個表參與:出貨量,ShipmentDetails和ShipmentWeights。所有三個表都通過出貨單的PK來鏈接。

在這段代碼,最終查詢(「權重」)失敗,出現錯誤:「不支持例外:與當地館藏查詢不被支持。」我收集了LinqToSql中的某些東西不支持使用.Contains,但我不明白查詢名爲「Details」的查詢是如何工作的。這似乎是對我來說同樣的一種查詢。有人可以填補我的空白嗎?

對於那些誰不熟悉LinqPad中,使用.dump方法是IQueryable的只是一個擴展方法,打印出格式化的方式的內容。

var shipments = Shipments.Where(s => s.OrderID == "Some OrderID"); 
shipments.Dump("Shipments"); 

var shipmentIds = shipments.Select(s => s.ShipmentID); 
shipmentIds.Dump(); 

    //This query works. What is different about this query than the one that fails? 
var shipmentDetails = ShipmentDetails.Where(d => shipmentIds.Contains(d.ShipmentID)); 
shipmentDetails.Dump("Details"); 

var detailShipmentIds = shipmentDetails.Select(sd => sd.ShipmentID); 
detailShipmentIds.Dump(); 

//This is the query that generates the error 
    var shipmentWeights = ShipmentWeights.Where(w => detailShipmentIds.Contains(w.ShipmentID)); 
shipmentWeights.Dump("Weights"); 
+0

http://stackoverflow.com/questions/1084339/working-around-linqtosqls -query-with-local-collections-are-not-supported-exce –

回答

2

你的列表是IQueryable的公司 - 即查詢沒有被執行又那麼它們不能被用作Contains查詢的一部分。只需將它們首先更改爲本地列表,然後這將工作。例如

var shipmentIds = shipments.Select(s => s.ShipmentID).ToList(); 

對所有本地列表都做同樣的事情。

這裏有一個完整列表

var shipments = Shipments.Where(s => s.OrderID == "Some OrderID"); 
shipments.Dump("Shipments"); 

var shipmentIds = shipments.Select(s => s.ShipmentID).ToList(); 
shipmentIds.Dump(); 

//This query works. What is different about this query than the one that fails? 
var shipmentDetails = ShipmentDetails.Where(d => shipmentIds.Contains(d.ShipmentID)); 
shipmentDetails.Dump("Details"); 

var detailShipmentIds = shipmentDetails.Select(sd => sd.ShipmentID).ToList(); 
detailShipmentIds.Dump(); 

//This is the query that generates the error 
var shipmentWeights = ShipmentWeights.Where(w => detailShipmentIds.Contains(w.ShipmentID)); 
shipmentWeights.Dump("Weights"); 
+0

但是爲什麼一個查詢可以與Contains(裝有ShipmentDetails的那個)一起工作而不使用ToList,而另一個則不是? –

+0

@Chris - 因爲當你進入最後的查詢時,你有4個延遲查詢與本地/遠程包含堆積在一起並增加了複雜性。基本上編譯器不能將你的查詢翻譯成SQL。 –

0

呀如指出的那樣,你將不得不做

var shipments = Shipments.Where(s => s.OrderID == "Some OrderID"); 
shipments.Dump("Shipments"); 

var shipmentIds = shipments.Select(s => s.ShipmentID).ToList(); 
shipmentIds.Dump(); 

    //This query works. What is different about this query than the one that fails? 
var shipmentDetails = ShipmentDetails.Where(d => shipmentIds.Contains(d.ShipmentID)); 
shipmentDetails.Dump("Details"); 

var detailShipmentIds = shipmentDetails.Select(sd => sd.ShipmentID).ToList(); 
detailShipmentIds.Dump(); 

//This is the query that generates the error 
    var shipmentWeights = ShipmentWeights.Where(w => detailShipmentIds.Contains(w.ShipmentID)); 
shipmentWeights.Dump("Weights"); 
+0

shipmentDetails的查詢不使用ToList,而那是我無法理解的部分。這兩個查詢有什麼區別? –