0

I have 3 classes. WorkoutSession, WorkoutSessionExercise and Exercise.

I would like to return the WorkoutSession with its list of WorkoutSession with the Exercise related. WorkoutSession has many WorkoutSessionExercise, and these one has only a single 1 to 1 relationship with Exercise.

             var query = from workoutSession in DatabaseContext.SetOwnable<WorkoutSession>()
             from workoutSessionExercises in workoutSession.WorkoutSessionExercises
             from exerciseInfo in workoutSessionExercises.Exercise
             where workoutSession.Id == id
             select workoutSession;

The last FROM has the error : The type argument cannot be inferred from the query.

How can I load this three level deep objects with Linq To Entity?

Patrick Desjardins
  • 136,852
  • 88
  • 292
  • 341

2 Answers2

1

Would something like this work?

DatabaseContext.SetOwnable<WorkoutSession>
    .Include("WorkoutSessionExercises.Exercise")
    .Where(w => w.Id == id);

Alternate syntax:

from workoutSession in DatabaseContext.SetOwnable<WorkoutSession>
    .Include("WorkoutSessionExercises.Exercise")
    where workoutSession.Id == id
    select workoutSession;

The key here is that Include method - this allows you to indicate which related objects should be hydrated.

Edit

Try this to get around the string-based includes (inspiration from Include nested entities using LINQ):

var query = from workoutSession in DatabaseContext.SetOwnable<WorkoutSession>
select new
{
     WorkoutSession,
     WorkoutSessionExercises = from workoutSessionExercise in
        DatabaseContext.SetOwnable<WorkoutSessionExercises>
        select new
        {
            WorkoutExercise = from workoutExercise in
                DatabaseContext.SetOwnable<WorkoutExercise>
                select workoutExercise
        }
};

var results = query.Select(r => r.WorkoutSession).Where(w => w.Id == id);
Community
  • 1
  • 1
nick_w
  • 14,758
  • 3
  • 51
  • 71
  • I'll give it a try when I come back to this project in few hours. Of course, what I dislike is the use of string but if it can work, it's better than nothing. – Patrick Desjardins Oct 15 '12 at 12:17
  • +1, this solution works well. Thank you. I will try to make work the solution of Diego which doesn't work for the moment because it's more "clean" than using String. Yours works and it's the goal for the moment. – Patrick Desjardins Oct 16 '12 at 00:45
  • Edited my answer with a string-free approach. – nick_w Oct 16 '12 at 01:44
0
var query = DatabaseContext.SetOwnable<WorkoutSession>()
                           .Include(x => x.WorkoutSessionExercises
                                          .Select(e => e.Exercise))
                           .Where(x => x.Id == id);
Diego Mijelshon
  • 52,548
  • 16
  • 116
  • 154