Linq。使用LinqPad选择方法问题

时间:2011-03-11 19:49:40

标签: c# linq-to-sql linqpad

我无法理解为什么在以下代码中出现错误。我确信我遗漏了一些简单的东西,但我需要帮助理解。

我一直使用LinqToSql在LinqPad中运行此代码。

我在LinqPad中有以下代码:

涉及三个表:Shipments,ShipmentDetails和ShipmentWeights。所有三个表都通过shipmentID链接,该货件ID是出货表的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");

2 个答案:

答案 0 :(得分: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");

答案 1 :(得分: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");
相关问题