我正在使用实体框架,当它到达最后一行时正在获取它:
方法'单身'和' SingleOrDefault'只能用作决赛 查询操作。考虑使用方法' FirstOrDefault'在这 实例而不是。
我的查询是:
var orderitems =
from orderItem in db.Order_ProductItem
join style in db.Products_Styles on orderItem.Style equals style.Index
where orderItem.SalesOrderID == salesOrderId &&
(orderItem.IsDeleted==null || orderItem.IsDeleted.Value == false)
group new { orderItem, style } by orderItem.FrameNo into grp
select new OrderItemModel
{
FrameNo = grp.Key,
//Count = grp.Select(x => x.orderItem.FrameNo).Count(),
TotalCost = grp.Sum(x => x.orderItem.CostPrice),
OverAllWidth = grp.Single(x => x.orderItem.HardwareType == 3).orderItem.OverallWidth,
OverAllHeight = grp.Single(x => x.orderItem.HardwareType == 3).orderItem.OverallHeight,
Name = grp.Select(x => x.style.Name).First(),
ImagePath = grp.Select(x => x.style.External_Image_Path).First()
};
var orders = orderitems.ToList();
似乎在LINQPad / Linq to SQL中工作正常....
任何想法有什么不对?
答案 0 :(得分:1)
Single()
和First()
之间存在差异。
OverAllWidth = grp.Single(x => x.orderItem.HardwareType == 3).orderItem.OverallWidth
如果查询返回多个结果,这将引发异常,这是完全可能的,因为可能有多个返回的项目是HadwareType 3. Single()期望一个返回值
改为使用First
或FirstOrDefault
。如果返回多个结果集,则将采用第一个结果集。
答案 1 :(得分:0)
我已经像这样更新了,它现在可以工作了......仍然很困惑为什么它在LINQPad中正好倾倒....
var orderitems =
from orderItem in db.Order_ProductItem
join style in db.Products_Styles on orderItem.Style equals style.Index
where orderItem.SalesOrderID == salesOrderId && (orderItem.IsDeleted==null || orderItem.IsDeleted.Value == false)
group new { orderItem, style } by orderItem.FrameNo into grp
select new OrderItemModel
{
FrameNo = grp.Key,
//Count = grp.Select(x => x.orderItem.FrameNo).Count(),
TotalCost = grp.Sum(x => x.orderItem.CostPrice),
OverAllWidth = grp.FirstOrDefault(x => x.orderItem.HardwareType == 3).orderItem.OverallWidth,
OverAllHeight = grp.FirstOrDefault(x => x.orderItem.HardwareType == 3).orderItem.OverallHeight,
Name = grp.FirstOrDefault().style.Name,//.FirstOrDefault(),
ImagePath = grp.FirstOrDefault().style.External_Image_Path//x => x.style.External_Image_Path)//.FirstOrDefault()
};
//var count = orderitems.Count();
var orders = orderitems.ToList();
答案 2 :(得分:0)
您确定查询正在执行相同的数据源吗?正如其他人所指出的,如果查询返回的序列没有一个元素,Single就会抛出异常。
答案 3 :(得分:0)
当LINQpad直接连接到数据库时,我遇到了类似的问题。如果将 LINQpad 连接到实体框架程序集而不是数据库,则 LINQpad 和 Visual Studio 的行为更接近相同。 为了连接到实体框架程序集,我关注了这个页面: https://www.vitoshacademy.com/c-entity-framework-using-linqpad5-for-queries-just-getting-started/