tags:

views:

63

answers:

1

This is quite straightforward:

I have three tables:
Questions:
ID (PK)
Body

QuestionsAndAnswers:
QuesionID
AnswerID

Answers:
ID
Body
IsCorrect

Each has a corresponding Class:

[Table]
public class Questions  
{  
  [Column]public int ID;  
  [Column]public string Body;  
}   

[Table]      
public class QuestionsAndAnswers   
{
  [Column]public int QuestionID;
  [Column]public int AnswerID;  
}  

[Table]
public class Answers
{
  [Column]public int AnswerID;  
  [Column]public string Body;
  [Column]public bool IsCorrect;
}  

I need to get a question with all it's answers.

I know how to get all the questions:

private Table<Questions> questionsTable;  
public SQLQuestionsRepository (string connString)  
{  
  questionsTable=(new DataContext(connString)).GetTable<Questions>();
}  

But how do I associate a specific one with it's answers?
Can I do it in one command or should I actually use linq queries? and if so, how?

Thank you.

+3  A: 

You may want to do a join (note that there is actually a join LINQ method you could use, but I'm not using it here):

using (var dataContext = new DataContext(connString)) {
  questionsTable=
             from q in dataContext.GetTable<Questions>()
             from a in dataContext.GetTable<Answers>()
             from qa in dataContext.GetTable<QuestionsAndAnswers>()
             where qa.QuestionID == q.QuestionID && qa.AnswerID == a.AnswerID
             select new { Question = q, Answer = a};
}

Another option would be to add association (navigation) properties so that you can get to the info you want right off of your Questions object:

[Association(Storage="QuestionsAndAnswers", OtherKey="QuestionID")]
public QuestionsAndAnswers QuestionsAndAnswers ...

Then you can simply fetch Questions and do

myQuestion.QuestionsAndAnswers[0].Answer.IsCorrect
JeffN825
Ahhh.. A lot to read about (-: Thanks.
Oren A
Should I use EntitySet<..> / EntityRef<..> ?
Oren A
If you're using the LINQ to SQL designer, it should add the attributes to the model classes automatically. Usually the private field it creates for -> 1 relationships is of type EntityRef<T>, but the public property is of type T (the entity). -> Many relationships are usually created as EntitySet<T>. But again, if you're using the designer, it should handle all of this for you...
JeffN825
Great, thanks .
Oren A