问题
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?
回答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);
回答2:
var query = DatabaseContext.SetOwnable<WorkoutSession>()
.Include(x => x.WorkoutSessionExercises
.Select(e => e.Exercise))
.Where(x => x.Id == id);
来源:https://stackoverflow.com/questions/12886510/returning-from-a-dbset-3-tables-without-the-error-cannot-be-inferred-from-the-q