C# - 基于另一个集合异常过滤集合

时间:2021-01-11 11:52:24

标签: c# linq collections filtering

我搜索了许多关于如何基于另一个集合过滤集合的示例,我找到了一种简单的方法,如下所示:

var oShipnotes = await DbContext.ShipNotes.Where(s => oManageRouteDto.ShipNotes.Any(mr => mr.Id == s.Id)).ToListAsync();

但是它抛出一个异常,说它不能转换为 SQL 查询。

谁能指出我如何解决这个问题的正确方向? 谢谢!

1 个答案:

答案 0 :(得分:1)

将嵌套的 LINQ 查询替换为物化标识符列表:

// 1) get the list of target ship note identifiers
var ids = oManageRouteDto.ShipNotes.Select(mr => mr.Id).ToList();

// 2) pass this list into Where using Contains
var oShipnotes = await DbContext.ShipNotes.Where(s => ids.Contains(s.Id)).ToListAsync();

EF 知道这种模式并将 IList<T>.Contains 转换为 SQL 的 IN 条件。

由于 EF 处理 IQueryable,因此每个 LINQ 查询都必须转换为有效的 SQL 表达式。因此,EF 和底层提供程序不能仅仅因为 SQL 不是 C# 就翻译每个有效的 LINQ 查询(从 C# 的角度来看)。