You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将关联查询SQL转换为Entity Framework Linq并返回C#列表

问题解决说明

报错根因

你写的代码触发编译错误的核心原因是:

  • Linq的Where方法要求传入的Lambda必须返回bool类型,你在外层Where内部调用了main.MainMapping.Where(...),该方法返回的是IEnumerable<MainMapping>集合,无法隐式转换为布尔值,直接触发CS0029和CS1662错误。
  • 额外优化点:你只需要查询Main表的ID字段,不需要调用Include加载关联的MainMapping数据,Include仅用于需要返回关联实体的场景,此处使用会增加不必要的查询开销。

修正方案

方案1:导航属性写法(最简洁,符合EF使用习惯)

直接将内层的Where替换为Any,只要存在匹配的关联记录就返回true,同时加Select只取ID字段,和你提供的SQL逻辑完全一致:

var listOfId = await _context.Main
    .Where(main => main.MainMapping
        .Any(mapping => request.SecondIdList.Contains(mapping.SecondId))
    )
    .Select(main => main.ID)
    .ToListAsync();

方案2:显式Join写法(和原SQL逻辑一一对应)

如果你的上下文中有MainMapping的DbSet,也可以直接写显式Join,和你给出的SQL执行逻辑完全匹配,注意加Distinct避免同一个MainID因为匹配多个SecondID返回重复结果:

var listOfId = await _context.Main
    .Join(_context.MainMapping,
        main => main.ID,
        mapping => mapping.MainId,
        (main, mapping) => new { main.ID, mapping.SecondId }
    )
    .Where(res => request.SecondIdList.Contains(res.SecondId))
    .Select(res => res.ID)
    .Distinct()
    .ToListAsync();

内容的提问来源于stack exchange,提问作者Zorev Gnoz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 14:06:03