LINQ查询WHERE SUM大于数字

时间:2018-01-08 23:20:01

标签: asp.net vb.net entity-framework linq

我在数据库中映射的仓库中有一系列货架。货架本身包含以立方英尺为单位测量的箱子。我想执行查询并过滤掉货架上最小量立方英尺的位置。我可以运行显示可用空间量的查询,但限制WHERE结果的SUM子句似乎没有任何效果。

以下是我的查询,以获得所有货架的可用空间和总空间:

Dim shelves As IQueryable(Of Location) = _db.Locations.Include(Function(l) l.Boxes)
    .Select(Function(loc) New With 
    {
        .LocationID = loc.LocationID,
        .WarehouseID = loc.WarehouseID,
        .Warehouse = loc.Warehouse.Name,
        .Row = loc.Row, 
        .Column = loc.Column, 
        .Bunk = loc.Bunk,
        .TotalSpace = loc.Footage,
        .FreeSpace = (loc.Footage - loc.Boxes.Select(Function(s) s.Size).DefaultIfEmpty(0).Sum()) 
     }).ToList()

这将返回每个位置的正确值,包括正确的可用空间量。当我引入WHERE子句时,它没有任何效果。以下是包含WHERE子句的查询:

Dim shelves As IQueryable(Of Location) = _db.Locations.Include(Function(l) l.Boxes)
    .Where(Function(l) (l.Boxes.Select(Function(e) e.Size).DefaultIfEmpty(0).Sum() >= EmptySpace))
    .Select(Function(loc) New With 
    {
        .LocationID = loc.LocationID,
        .WarehouseID = loc.WarehouseID,
        .Warehouse = loc.Warehouse.Name,
        .Row = loc.Row, 
        .Column = loc.Column, 
        .Bunk = loc.Bunk,
        .TotalSpace = loc.Footage,
        .FreeSpace = (loc.Footage - loc.Boxes.Select(Function(s) s.Size).DefaultIfEmpty(0).Sum()) 
     }).ToList()

由于.FreeSpace返回正确的值,我不确定为什么它不能在我的WHERE子句中按相同的值进行过滤。

1 个答案:

答案 0 :(得分:1)

更新

你原来的谓词

.Where(Function(l) (l.Boxes.Select(Function(e) e.Size).DefaultIfEmpty(0).Sum() >= EmptySpace))

没有计算自由空间,这就是它没有效果的原因。

您会注意到,在初始选择中,您计算​​的可用空间为

(loc.Footage - loc.Boxes.Select(Function(s) s.Size).DefaultIfEmpty(0).Sum())

Where谓词中缺少注意loc.Footage

这意味着此更新的查询应该有效

Dim shelves As IQueryable(Of Location) = _db.Locations.Include(Function(l) l.Boxes)
    .Where(Function(loc) (loc.Footage - loc.Boxes.Select(Function(s) s.Size).DefaultIfEmpty(0).Sum()) >= EmptySpace)
    .Select(Function(loc) New With 
    {
        .LocationID = loc.LocationID,
        .WarehouseID = loc.WarehouseID,
        .Warehouse = loc.Warehouse.Name,
        .Row = loc.Row, 
        .Column = loc.Column, 
        .Bunk = loc.Bunk,
        .TotalSpace = loc.Footage,
        .FreeSpace = (loc.Footage - loc.Boxes.Select(Function(s) s.Size).DefaultIfEmpty(0).Sum()) 
     }).ToList()

原始答案

尝试在选择

后对投影对象应用滤镜
Dim shelves As IQueryable(Of Location) = _db.Locations.Include(Function(l) l.Boxes)    
.Select(Function(loc) New With 
{
    .LocationID = loc.LocationID,
    .WarehouseID = loc.WarehouseID,
    .Warehouse = loc.Warehouse.Name,
    .Row = loc.Row, 
    .Column = loc.Column, 
    .Bunk = loc.Bunk,
    .TotalSpace = loc.Footage,
    .FreeSpace = (loc.Footage - loc.Boxes.Select(Function(s) s.Size).DefaultIfEmpty(0).Sum()) 
 })
.Where(Function(loc) loc.FreeSpace >= EmptySpace)
.ToList()

这样,可用空间已经计算并包含在匿名对象中。