2012-12-19 19 views
1

我正在创建一个问卷画面,我需要显示带有问题的部分以及用户的回复。这里是我的模型:如何查询有问题的部分及其答案?

** 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不工作):

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

与节你怎么链接的问题? – Ulises

+0

我刚刚更新了我的问题。 “SectionId”在与Section关联的Question模型中缺失。 – Chaka

+0

最后一个问题。我注意到,当没有答案时,它不返回任何问题..有没有相当于LINQ的左/右外连接?如果返回所有问题都返回? – Chaka

回答

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>  
    } 
} 
+0

我为被称为测验的视图创建了一个新模型,该测验具有以下属性:sectionId,sectiontext,ICollection 结果(也创建了结果模型)..收到以下错误: – Chaka

+0

传入字典的模型项类型为'System .Data.Entity.Infrastructure.DbQuery'1 [<> f__AnonymousType3'3 [System.Int32,System.String,System.Collections.Generic.IEnumerable'1 [<> f__AnonymousType2'6 [System.Int32,System.Int32,系统.String,System.Nullable'1 [System.Int32],System.String,System.String]]]]',但此字典需要类型为'System.Collections.Generic.IEnumerable'1的模型项目[COPSGMIS.Models 。测验]'。 – Chaka

+0

不知道如何包装结果以便将其显示到视图(MVC)?我迷路了。 – Chaka