I’ve been beating around on this thing all day and it’s driving me nuts!
What I’m trying to do:
I have 2 tables: Questions / Answers
The questions table consists of: quesID, quesDescr
The answers table consists of: answerID, quesID, answer
Basically, the answers table are the options for each question. For example:
quesID | quesDescr
1 | What is your favorite color?
answerID | quesID | answer
1 | 1 | Red
2 | 1 | Blue
etc…
On my form page I want to grab the questions and all their answer choices to display to the end user. It seems I can get the questions to list but I can’t get both the questions and answers to post on my View.
I thought I would handle the query (linq to sql) in my model… but this doesn’t give me the answers:
public List<nonEEPreQue> getPreQuestions()
{
return fDB.nonEEPreQues.OrderBy(q => q.preQuesOrder).ToList();
}
I read some things here and across that web that use outer joins. I think this might be correct, but I’m struggling with how to pass the variable. I tried this in the Model, but it seems it goes into the controller(?):
var quesList = from ques in preQ.nonEEPreQues
join an in preQ.nonEEPreQuesAnswers
on ques.preQuesID equals an.preQuesID into outer
from an in outer.DefaultIfEmpty()
select new
{
QuestionTxt = ques.preQuesDescr,
AnswerTxt = an.answerTxt
};
return View(quesList);
So – is the above correct? What do I do then in my view to access both question and answers (I assume in a foreach loop)?
Any help is greatly appreciated!
Since you’re already using Linq to SQL and using an anonymous type, keep it simple and select what you need in a relational manner.
This will give you an object that has QuestionTxt and QuestionID for the questions and a collection of
nonEEPreQuesAnswerobjects that are attached to question directly. This will make enumerating them easier, and it should be bindable as well (if you were doing a gridview or repeater).