2011-03-11 84 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,而那是我无法理解的部分。这两个查询有什么区别? –