简体   繁体   English

EF Core 3.1 - 包含过滤抛出错误“包含内部使用的 Lambda 表达式无效。”

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

I have Item table(Main) and ItemAlt table(Sub (List)) I want to get all item alt rows where:我有 Item table(Main) 和 ItemAlt table(Sub (List)) 我想获取所有 item alt 行,其中:

  1. ItemAlt.WarehouseId is equal to parameter warehouseId ItemAlt.WarehouseId 等于参数warehouseId

  2. Item.Id is equal to parameter itemId 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(); }

the problem is it throws the exception " Lambda expression used inside Include is not valid " in问题是它抛出异常“包含中使用的 Lambda 表达式无效

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

Do you know how to get around this issue?你知道如何解决这个问题吗?

  • I already tried searching for the error message but the queries are different from mine我已经尝试搜索错误消息,但查询与我的不同

Filtered includes are feature available only since EF Core 5.0 as docs state:过滤包含的功能仅在 EF Core 5.0 之后才可用, 文档state:

This feature was introduced in EF Core 5.0.此功能是在 EF Core 5.0 中引入的。

So you need either to update your project to corresponding .NET and EF Core versions or rewrite query to manual join with filtered ItemAlt 's.因此,您需要将项目更新为相应的 .NET 和 EF Core 版本,或者将查询重写为使用过滤后的ItemAlt手动加入。

Or try to select into anonymous type and rely on the relationship fixup.或者尝试将 select 转换为匿名类型并依赖关系修复。 Something along this lines (not tested):沿着这条线的东西(未经测试):

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM