Search code examples
asp.net-mvc-3liststored-proceduresentity-framework-4

Adding subitems to a mvc model without needing to loop thru a list?


Using mvc 3 with EF 4.1 (with stored procedures). I have a list of issues and I need to include a list of comments to each issue. Not sure how if this can be done in one proc and one model without looping thru each issue model and adding comments. Here's what I have so far: (In short need a better approach)

My procedure "SP_GetQuestionIssues":

CREATE PROC [dbo].[SP_GetQuestionIssues]
(@ReviewID int)
AS
Select r.ReviewID, q.QuestionId, s.Title Step, q.QuestionText Question, r.AnswerValue Answer, IsIssue 
From dbo.Questions q
 Join dbo.Steps s
            on q.StepId = s.StepId
 Join dbo.QuestionFlagged qf
            on q.questionId = qf.questionId 
 Join dbo.Responses r
            on q.questionId = r.QuestionID
 Where IsIssue=1 
 AND r.ReviewID = @ReviewID
 AND qf.ReviewID = @ReviewID
 Order by s.StepID, s.stepOrder, q.DisplayOrder

My model "QuestionIssue":

public class QuestionIssue
    {
        public int ReviewID { get; set; }
        public int QuestionId { get; set; }
        public string Step { get; set; }
        public string Question { get; set; }
        public string Answer { get; set; }
        public bool IsIssue { get; set; }
        public virtual IEnumerable<Comment> Comments { get; set; }
    }

My model "Comment":

public class Comment
    {      
            public int CommentId { get; set; }
            public int ReviewId { get; set; }
            public Nullable<int> QuestionId { get; set; }
            public string Reviewer { get; set; } 
            public string CommentText { get; set; } 
            public bool IsMemo { get; set; } 
    }

My action:

SqlParameter param = new SqlParameter("@ReviewID", Id);
                var issues = db.Database.SqlQuery<QuestionIssue>("SP_GetQuestionIssues @ReviewID", param).ToList();

Need a better approach than this (psuedo code):

 foreach(var issue in issues)
 {
     var comments = somefunction.getcomments(issue.reviewId, issue.questionId)
     issue.Comments.add(comment)
  }

Solution

  • I stumbled on this question 3 years later, but for what it's worth:

    You could have looked at a stored procedure that returns multiple recordsets (batch t-sql), and using SqlDataReader.NextResult to process them similarly to your pseudo code.