© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•3y ago•
7 replies
bookuha

❔ Why .Where() doesn't work with .Include()?

I need to fetch chats that have current user as a participant, and want to fetch only active users.

I execute the following query:

var query = _db.Chats
            .Include(c => c.Participants.Where(cu=>cu.IsActive))
            .Include(c=>c.LastMessage)
            .ThenInclude(m => m.Sender)
            .ThenInclude(cu => cu.User)
            .Where(c =>
                c.Participants.Any(cu => cu.UserId == _currentUser.MessengerUserId))
            .OrderByDescending(c => c.LastMessage != null ? c.LastMessage.Timestamp : c.Created)
            .AsNoTracking();
var query = _db.Chats
            .Include(c => c.Participants.Where(cu=>cu.IsActive))
            .Include(c=>c.LastMessage)
            .ThenInclude(m => m.Sender)
            .ThenInclude(cu => cu.User)
            .Where(c =>
                c.Participants.Any(cu => cu.UserId == _currentUser.MessengerUserId))
            .OrderByDescending(c => c.LastMessage != null ? c.LastMessage.Timestamp : c.Created)
            .AsNoTracking();


but participants filtering part doesn't work - all the users are included, while it works as intended with 'select only chats with current user as participant' condition.

https://i.stack.imgur.com/WDA6h.png - Code with Resharper Annotations
https://pastebin.com/Bvsxju91 - Generated PgSql script

https://stackoverflow.com/questions/76157093/why-where-doesnt-work-with-include - SO question
Preview image
Pastebin
sql - Pastebin.com
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Stack Overflow
Why .Where() doesn't work with .Include()?
I need to fetch chats that have current user as a participant, and want to fetch only active users.
I execute the following query:
var query = _db.Chats
.Include(c => c.Participants....
Why .Where() doesn't work with .Include()?
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources
Was this page helpful?

Similar Threads

Recent Announcements

Similar Threads

why this doesn't work
C#CC# / help
2y ago
✅ why doesn't this work?
C#CC# / help
3y ago
❔ Why doesn't this button work?
C#CC# / help
3y ago