Returning from a DbSet 3 tables without the error “cannot be inferred from the query”

帅比萌擦擦* 提交于 2019-12-08 13:44:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!