EF Core 3.1 - 包含过滤引发错误 'Lambda expression used inside Include is not valid.'

EF Core 3.1 - Include filtering throw an error 'Lambda expression used inside Include is not valid.'

我有 Item table(Main) 和 ItemAlt table(Sub (List)) 我想获取所有项目替代行,其中:

  1. ItemAlt.WarehouseId等于参数warehouseId

  2. Item.Id等于参数itemId

    public async Task<Item> GetItemWithAlt(int itemId, int warehouseId)
    {
        var query = from i in _dbContext.Item.Include(a => a.ItemAlt.Where(c => c.WarehouseId == warehouseId && c.IsActive == true))
                    where i.IsActive.Equals(true) && i.Id.Equals(itemId)
                    select i;
        return await query.SingleOrDefaultAsync();
    }
    

问题是它在

中抛出异常“Include 中使用的 Lambda 表达式无效

.Where(c => c.WarehouseId == warehouseId && c.IsActive == true)

你知道如何解决这个问题吗?

过滤包含仅在 EF Core 5.0 之后可用,因为 docs 状态:

This feature was introduced in EF Core 5.0.

因此,您需要将项目更新到相应的 .NET 和 EF Core 版本,或者将查询重写为手动加入已过滤的 ItemAlt

或尝试select 成匿名类型并依靠关系修复。沿着这条线(未测试):

var result = await _dbContext.Item
    .Where(i => i.IsActive.Equals(true) && i.Id.Equals(itemId))
    .Select(i => new 
    {
        Item = i,
        ItemAlts = i.ItemAlt
            .Where(c => c.WarehouseId == warehouseId && c.IsActive == true))
            .ToList()
    }
    .SingleOrDefaultAsync();

return result?.Item;