从存储过程结果创建对象

LCJ*_*LCJ 7 c# linq sql-server stored-procedures

我们有一个现有的SQL Server存储过程以及以下查询.我们需要Student从查询结果中创建以下类设计中的对象集合.

SqlDataReader使用中创建对象的最佳方法是什么LINQ

注意:我SqlDataReader只使用; 没有ORM

询问

SELECT 
    S.StudentID, S.StudentName, E.ExamID, E.ExamName, SE.Mark 
FROM 
    StudentExam SE
INNER JOIN 
    Student S ON S.StudentID = SE.StudentID
INNER JOIN 
    Exam E ON E.ExamID = SE.ExamID 
Run Code Online (Sandbox Code Playgroud)

public class ExamMark
{
    public int ExamID { get; set; }
    public string ExamName { get; set; }
    public int Mark { get; set; }
}

public class Student
{
    public int StudentID { get; set; }
    public string StudentName { get; set; }
    public List<ExamMark> examResults { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

SqlDataReader的

   SqlDataReader reader = command.ExecuteReader();
   if (reader.HasRows)
   {
      while (reader.Read())
      {

      }
   } 
Run Code Online (Sandbox Code Playgroud)

参考

  1. LINQ:从左连接填充对象
  2. DataTable上的复杂GROUP BY

Jod*_*ell 5

好吧,我不会那样做,

我有两个陈述

-- Student Statement
SELECT
             S.StudentID,
             S.StudentName
    FROM
             Student S
    WHERE
             EXISTS (
              SELECT * FROM StudentExam SE WHERE SE.StudentID = S.Student.ID);

-- Exam Statement
SELECT
            SE.StudentID,
            E.ExamID,
            E.ExamName,
            SE.Mark 
    FROM
            StudentExam SE
        JOIN
            Exam E
                ON E.ExamID = SE.ExamID;
Run Code Online (Sandbox Code Playgroud)

然后,我有一个功能,这样做,

private IEnumerable<Tuple<int, ExamMark>> GetMarks()
{
    ... setup the exam command here
    var reader = examCommand.ExecuteReader();
    while (reader.Read())
    {
        yield return Tuple.Create(
            reader.GetInt32(0),
            new ExamMark
                {
                    reader.GetInt32(1),
                    reader.GetString(2),
                    reader.GetInt32(3)
                });
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我有这个功能来打电话,

private IEnumerable<Student> GetStudents()
{
    var resultLookup = GetMarks().ToLookup(t => t.Item1, t => t.Item2);

    ... setup the student command here
    var reader = studentCommand.ExecuteReader();
    while (reader.Read())
    {
        var studentId = reader.GetInt32(0);
        yield return new Student
                {
                    studentId,
                    reader.GetString(1),
                    resultLookup[studentId].ToList()
                });
    }
}
Run Code Online (Sandbox Code Playgroud)

如果需要,可以在一个存储过程中完成所有操作并返回多个结果集.