user1186050 user1186050 - 15 days ago 7
C# Question

Entity Framework throwing error when fetching a nested object using .include

I have a query here that fetches a single entity object and only one nested entity that meets a specific condition, but I'm receiving an error when executing it.

Here is the query

Profile profile = dbContext.Profiles.Where(i => i.ApplicationUserGuid == guiId)
.Include(i => i.ProfileImages.Where(k => k.IsMainImage == true)).First();


And here is the exception error message


The Include path expression must refer to a navigation property defined on the type. Use dotted paths for reference navigation properties and the Select operator for collection navigation properties.
Parameter name: path


I also tried running it with another .First(), but still same error message

Profile profile = dbContext.Profiles.Where(i => i.ApplicationUserGuid == guiId)
.Include(i => i.ProfileImages.Where(k => k.IsMainImage == true).First()).First();

Answer

You can't filter related entities inside an Include, you are going to need to project your query with the expected result or use explicit loading:

Profile profile = dbContext.Profiles
                           .Where(i => i.ApplicationUserGuid == guiId)
                           .First();
dbContext.Entry(profile) //Explicit Loading
         .Collection(b => b.ProfileImages) 
         .Query() 
         .Where(k => k.IsMainImage == true).Take(1)
         .Load(); 

If you do the projection it will be only one round trip to your database, and if you use explicit loading it will be two.

Just a FYI, in case you think to project the result, project to an anonymous type or onto a DTO. More info here.

Comments