AnimaSola AnimaSola - 1 month ago 18
C# Question

EF Lambda: The Include path expression must refer to a navigation property

Here is my expression:

Course course = db.Courses
.Include(
i => i.Modules.Where(m => m.IsDeleted == false)
.Select(s => s.Chapters.Where(c => c.IsDeleted == false))
).Include(i => i.Lab).Single(x => x.Id == id);


I know the cause is
Where(m => m.IsDeleted == false)
in the Modules portion, but why does it cause the error? More importantly, how do I fix it?

If I remove the where clause it works fine but I want to filter out deleted modules.

Answer

.Include is used to eagerly load related entities from the db. I.e. in your case make sure the data for modules and labs is loaded with the course.

The lamba expression inside the .Include should be telling Entity Framework which related table to include.

In your case you are also trying to perform a condition inside of the include, which is why you are receiving an error.

It looks like your query is this:

Find the course matching a given id, with the related module and lab. As long as the matching module and chapter are not deleted.

If that is right, then this should work:

Course course = db.Courses.Include(c => c.Modules)
                          .Include(c => c.Lab)
                          .Single(c => c.Id == id && 
                                       !c.Module.IsDeleted &&
                                       !c.Chapter.IsDeleted);