I’m using ASP.NET MVC 3 with Entity Framework CodeFirst
I have two classes as follows:
Question:
public class Question
{
public int ID { get; set; }
public Target Target { get; set; }
public string QuestionText { get; set; }
public Category Category { get; set; }
public QuestionType QuestionType { get; set; }
public virtual ICollection<Answer> Answers { get; set; }
public Unit Unit { get; set; }
}
Answer:
public class Answer
{
public int ID { get; set; }
public virtual Question Question { get; set; }
public string AnswerText { get; set; }
public int Value { get; set; }
}
I also have this ViewModel:
public class QuestionViewModel
{
public int ID { get; set; }
public string Question { get; set; }
public string QuestionType { get; set; }
public string Target { get; set; }
public string Category { get; set; }
public string Unit { get; set; }
public List<Answer> Answers { get; set; }
}
I want to query the questions table and include the answers, if there are any.
I’ve been trying this style
var question = (from q in hontgen.Questions
where q.ID == id
join qt in db.QuestionTypes on q.QuestionType equals qt
join t in db.Targets on q.Target equals t
join c in db.Categories on q.Category equals c
join u in db.Units on q.Unit equals u
join a in db.Answers on q.Answers equals a
select new QuestionViewModel() {
ID = q.ID,
Question = q.QuestionText,
QuestionType = qt.Type,
Category = c.CategoryName,
Unit = u.UnitName,
Target = t.TargetName,
Answers = a
}).Single();
But this of course doesn’t roll, because a isn’t a list of answers, but only one answer.
How do I rewrite the query to take all answers in the collection, or all answers with the correct question in “Question”, while at the same time accepting an empty answers-list?
What about a sub query like the following
}