我有一段代码,它结合了内存列表和数据库中保存的一些数据.这在我的单元测试中运行得很好(使用一个使用List的模拟Linq2sqlRepository).
public IRepository<OrderItem> orderItems { get; set; } private List<OrderHeld> _releasedOrders = null; private List<OrderHeld> releasedOrders { get { if (_releasedOrders == null) { _releasedOrders = new List<nOrderHeld>(); } return _releasedOrders; } } ..... public int GetReleasedCount(OrderItem orderItem) { int? total = ( from item in orderItems.All join releasedOrder in releasedOrders on item.OrderID equals releasedOrder.OrderID where item.ProductID == orderItem.ProductID select new { item.Quantity,} ).Sum(x => (int?)x.Quantity); return total.HasValue ? total.Value : 0; }
Exception information:
Exception type: System.NotSupportedException
Exception message: Local sequence cannot be used in LINQ to sql
implementation of query operators
except the Contains() operator.
我究竟做错了什么?
我猜这与orderItems在数据库上并且releasedItems在内存中的事实有关.
编辑
我根据给出的答案更改了我的代码(谢谢大家)
public int GetReleasedCount(OrderItem orderItem) { var releasedOrderIDs = releasedOrders.Select(x => x.OrderID); int? total = ( from item in orderItems.All where releasedOrderIDs.Contains(item.OrderID) && item.ProductID == orderItem.ProductID select new { item.Quantity,} ).Sum(x => (int?)x.Quantity); return total.HasValue ? total.Value : 0; }
解决方法
I’m guessing it’s to do with the fact
that orderItems is on the database
and releasedItems is in memory.
你是对的,你不能使用LINQ将表连接到List.
看看这个链接:
http://flatlinerdoa.spaces.live.com/Blog/cns!17124D03A9A052B0!455.entry
他建议使用Contains()方法,但你必须使用它来查看它是否适合你的需要.