2

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

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

我在 LinqPad 中有以下代码:

涉及三个表:Shipments、ShipmentDetails 和 ShipmentWeights。所有三个表都由 shippingID 链接,它是 Shipments 表的 PK。

在此代码中,最终查询(“权重”)失败并出现错误:“不支持的异常:不支持具有本地集合的查询。” 我收集到 LinqToSql 中的某些内容不支持使用 .Contains 但我不明白名为“详细信息”的查询是如何工作的。对我来说,这似乎是同一种查询。有人可以为我填补空白吗?

对于不熟悉 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");
4

2 回答 2

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");
于 2011-03-11T20:09:13.280 回答
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");
于 2011-03-11T20:09:27.990 回答