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.

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

2 Comments

Should I use EntitySet<..> / EntityRef<..> ?
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...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.