【问题标题】:I want to convert SQL to Linq query [closed]我想将 SQL 转换为 Linq 查询 [关闭]
【发布时间】:2021-01-19 17:01:32
【问题描述】:

这是我想要转换成 Linq 的 SQL 查询

SELECT 
    s.Studentname,
    COUNT(c.StudentId)
FROM  
    Students s, StudentCourses c
WHERE 
    s.StudentId = c.StudentId
GROUP BY
    s.Studentname

这里正在尝试使用 linq 将数据存储在 StudentDto 模型中

var students = (from s in DbContext.students
                    join sc in DbContext.studentCourses on 
                    s.StudentId equals sc.StudentId
                    group s by s.Studentname into grouped
                    select new StudentDto()
                    {
                        Studentname = s.StudentName,
                        StudentEmail = s.StudentEmail,
                        PhoneNumber = s.PhoneNumber,
                        DateOfBirth = s.DateOfBirth,
                        Password = s.Password,
                        ConfirmPawword = s.ConfirmPawword,
                        CourseCount = sc.count()
                    }
                    ).ToList();
    

【问题讨论】:

  • Bad habits to kick : using old-style JOINs - 旧式 逗号分隔的表格列表 样式已替换为 ANSI 中的 proper ANSI JOIN 语法-92 SQL 标准(25 多年前),不鼓励使用它
  • 你有什么尝试?在询问您的家庭作业之前,请阅读 SO 指南。
  • 这将是您第一次使用 linq 的完美示例。 linqsamples.com
  • 总是提到 EF 版本并显示类模型。如果没有这种信息,我们只能猜测哪种解决方案是可能的。

标签: sql sql-server entity-framework linq


【解决方案1】:

一个惯用的 LINQ 查询就是:

from s in db.Students
select new {s.StudentName, CourseCount = s.Courses.Count() };

【讨论】:

  • 我想用 studentName 分组
  • 除非多个学生具有相同的 StudentName,否则您不需要这样做。我的答案中的查询为每个学生返回一行。
  • 是的。无需加入。只需查询学生并使用课程导航属性进行计数。
猜你喜欢
  • 2015-06-08
  • 2021-01-28
  • 1970-01-01
  • 1970-01-01
  • 2021-11-29
  • 1970-01-01
  • 2018-07-31
  • 1970-01-01
  • 2014-08-14
相关资源
最近更新 更多