1

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();

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

19 Comments

I'm following your explicit loading example and its working but it's returning all the nested entities and not just the one that meets the where condition!
I have edited my answer, Take method should fix that
I'm still a little unsure why all images are being returned when all except 1 meet the where condition? Then what's the purpose of the where condition? If it's not working? And I tried Take(1) and it still returns all the images!
Oh, just one meet the condition? Are you completely sure? Did you check your db?
What I always do is disable lazy loading and use eager loading instead when I need some nav prop, but maybe your design works better with lazy loading. That property is being loaded because it has been accessed in some point in your code. Projecting your queries to ViewModel classes is a good practice, you will find good tutorials if your search a little.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.