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

如何将SQL SELECT语句转换为LINQ并在Index控制器Action中使用

LINQ转换实现方案

你原有代码的语法问题主要有3处:

  • LINQ不支持直接写not in语法,需要借助整数列表+!Contains()实现排除逻辑
  • 匿名对象投影语法错误,Distinct()方法的调用位置不对
  • 缺失了programId、custId过滤条件、排序规则,以及Test count字段的投影

可直接在Statistics Action中使用的代码如下:

public ActionResult Statistics(int programId, int custId)
{
    // 预定义需要排除的测试ID集合
    var excludedIds = new List<int> { 51, 52, 54, 55, 56, 57, 60, 1125, 3161 };

    var stat = (from programTest in _context.programs_tests
                join labTest in _context.LabTests on programTest.testid equals labTest.TestId
                where !excludedIds.Contains(labTest.TestId)
                      && programTest.programId == programId
                      && programTest.custid == custId
                orderby labTest.testname
                select new
                {
                    testid = programTest.testid,
                    testname = labTest.testname,
                    TestCount = string.Empty
                }).Distinct().ToList();

    // 按需将查询结果传入视图即可
    return View(stat);
}

补充:如果你的EF实体已经配置了programs_tests和LabTests之间的导航属性,可以省略手动join的步骤,直接通过导航属性获取关联的检验项数据,写法会更简洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 01:57:16