4

How do I include a 2nd level table column in my linq query? I don't want .Net to perform lazy loading because there are other tables linked to these tables.

The table are

Quiz:    
 - Id
 - Name

Questions:    
 - Id
 - Name
 - quizId

Options:   
 - id
 - Name
 - QuestionId

Quiz and Questions have a one-to-many relationship. Questions to Option also have a one-to-many relationship.

var quiz=db.Quiz.include(a=>a.Questions)......ToList();

How can I include Options columns in my linq query?

ryanyuyu
  • 6,366
  • 10
  • 48
  • 53

3 Answers3

2

If you want to eargerly load grandchildren of an entity, the code below will achieve this, provided you have mapped the relationships correctly.

var quiz = db.Quiz
             .Include(a => a.Questions.Select(q => q.Options))
             .ToList();
Luke
  • 22,826
  • 31
  • 110
  • 193
Prabu
  • 4,097
  • 5
  • 45
  • 66
0

Add to Questions property Options as ICollection and mapping as one to many. Then You may use

var quiz=db.Quiz.include(a=>a.Questions).include(a=>a.Questions.Options).......ToList();

Or

  • 1
    I'm pretty sure that this won't work though cause it's multiple `Questions` and that multiple object won't have an `Options` property. Each one in the collection will though – Luke Aug 14 '15 at 13:46
  • Indeed, but did the other suggestions? – Luke Aug 14 '15 at 15:36
0

I'm pretty sure that you can just do multiple Include()s:

var quiz = db.Quiz
           .Include(x => x.Questions)
           .Include("Questions.Options")
           .ToList();

It's not completely strongly typed though like @pwee167's answer, however it is descriptive for each collection that you want to have included in your query.

Luke
  • 22,826
  • 31
  • 110
  • 193