SQL转LINQ多表Inner Join时报Expected contextual keyword 'on'错误如何解决
LINQ语句错误排查与修复方案
错误原因
你遇到的报错核心原因有两个:
- 遗漏了原SQL中
resp.segmentid = 4的过滤条件,LINQ的join语法不支持直接在on子句中追加非等值的额外关联条件,如果你直接在on后面加过滤逻辑会触发编译器语法错误。 - 你写的
select子句中raoe.AreaofExp拼写和字段名不匹配,原SQL要取的是raoe.AreaofExpID,属性名拼写错误会导致编译器误判语法结构,抛出「Expected contextual keyword 'on'」的误报。
正确实现代码
推荐先过滤Response表再做关联,执行效率和原SQL完全一致:
var query = from aoe in _cctDBContext.AreaOfExp join raoe in _cctDBContext.ResponseAreaOfExp on aoe.AreaofExpId equals raoe.AreaofExpId // 先过滤符合segmentid=4的Response数据再关联 join resp in _cctDBContext.Response.Where(r => r.SegmentId == 4) on raoe.ResponseId equals resp.ResponseId select new { raoe.AreaofExpId, aoe.ServiceLineId, raoe.ResponseId };
如果习惯用关联后过滤的写法,也可以用下面的实现,最终执行效果和上面完全相同:
var query = from aoe in _cctDBContext.AreaOfExp join raoe in _cctDBContext.ResponseAreaOfExp on aoe.AreaofExpId equals raoe.AreaofExpId join resp in _cctDBContext.Response on raoe.ResponseId equals resp.ResponseId where resp.SegmentId == 4 select new { raoe.AreaofExpId, aoe.ServiceLineId, raoe.ResponseId };
内容的提问来源于stack exchange,提问作者Jason_Hough
相关产品推荐
相关产品推荐

