如何查询有问题的部分及其答案?

时间:2012-12-19 19:17:28

标签: c# asp.net-mvc linq entity-framework

我正在创建一个问卷屏幕,我需要显示有问题的部分以及用户的回复。这是我的模特:

** Section *****
 public int SectionID { get; set; }
 public string SectionText { get; set; }

** Question ****
 public int QuestionID { get; set; }
 public int SectionID { get; set; }
 public string QuestionText { get; set; }
 public bool Required { get; set; }
 public int DisplayOrder { get; set; }

** Response ****
 public int ResponseID { get; set; }
 public int UserID { get; set; }
 public int QuestionID { get; set; }
 public string AnswerValue { get; set; }
 public virtual Question Question { get; set; }

如何通过LINQ或其他方法获取此信息以显示以下内容:

Section1: User Info
        Question 1. Name:  Bob Smith
        Question 2. Phone: 999-999-9999

Section2: User Tasks
         Question 1. Role: Engineer
         Question 2. Location: Baltimore

我尝试了以下(deos not work):

var sections = from b in db.Sections.Include(s => s.Questions.Select(q => q.Responses.Where(r => r.userId == 1))
                            orderby b.SectionOrder
                            select b;

1 个答案:

答案 0 :(得分:1)

int userId = 1;
var query = from s in db.Sections
            join r in db.Responses.Where(x => x.UserID == userId)
                   on s.SectionID equals r.Question.SectionID into g
            select new SectionModel
            {
                ID = s.SectionID,
                Name = s.SectionText,
                Results = from x in g
                          orderby x.Question.DisplayOrder
                          select new QuestionResultModel
                          {
                              Index = x.Question.DisplayOrder,
                              Question = x.Question.QuestionText,
                              Answer = x.AnswerValue
                          }
            };

  return View(query.ToList());

更新 ViewModel样本:

public class SectionModel
{
    public int ID { get; set; }
    public string Name { get; set; }
    public IEnumerable<QuestionResultModel> Results { get; set; }
}

public class QuestionResultModel
{
    public int Index { get; set; }
    public string Question { get; set; }
    public string Answer { get; set; }
}

显示:

@model IEnumerable<YourApplication.Models.SectionModel>

@foreach (var s in Model)
{
    <div>Section @s.ID : @s.Name</div>

    foreach (var r in s.Results)
    {
        <div>Question @r.Index. @r.Question : @r.Answer</div>    
    }
}