2012-12-19 25 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