3

Is it possible in linq to use single include instead of this :

     _db.UserQuizes.Where(uq => uq.UserId == currentUserId && uq.QuizId == quizId)
.Include(qz => qz.Quiz.VerbalQuizes.Select(q => q.Question.Answers))
.Include(qz => qz.Quiz.MathQuizes.Select(q => q.Question.Answers))
.Include(qz => qz.Quiz.VerbalQuizes.Select(q => q.Question.TaskWithMultipleQuestion))
.Include(qz => qz.Quiz.MathQuizes.Select(q => q.Question.TaskWithMultipleQuestion))
.Include(qz => qz.Quiz.VerbalQuizes.Select(q => q.Question.QuestionTags.Select(m => m.Tag)))
.Include(qz => qz.Quiz.MathQuizes.Select(q => q.Question.QuestionTags.Select(m => m.Tag)))
.Include(qz => qz.Quiz.MathQuizes.Select(q => q.Question.Answers))
.First();

What i want to achive is write linq something like this :

_db.UserQuizes.Where(uq => uq.UserId == currentUserId && uq.QuizId == quizId)
                     .Include(qz => qz.Quiz.VerbalQuizes.Select(q => new{
                        ans =  q.Question.Answers,
                        mult = q.Question.TaskWithMultipleQuestion,
                        tag =  q.Question.QuestionTags.Select(m => m.Tag)
                     }))
                      .Include(qz => qz.Quiz.MathQuizes.Select(q => new
                      {
                          ans = q.Question.Answers,
                          mult = q.Question.TaskWithMultipleQuestion,
                          tag = q.Question.QuestionTags.Select(m => m.Tag)
                      })).First();

Also is it a bad practise to use so much include in a simple query? Is it better to split up? But if it is what would be the best way? write seven queries?

_db is just an object for connect to database

 EFDbContext _db = new EFDbContext();
ucnobi ucnobi
  • 255
  • 1
  • 5
  • 16

1 Answers1

1

Look at this MSDN page says:

Include() is an “exact-entity” operator of ObjectQuery.

(Reference: http://msdn2.microsoft.com/en-us/library/bb738708(VS.90).aspx) It denotes a navigation property that you want to dereference and materialize as part of your resulting entity collection. That’s why the “T” in the ObjectQuery must be an entity type, i.e. it may not be DbDataRecord. In the first case all the clauses produce such interim ObjectQuery instances.

So you cant use like this Include(anonymous type)