Skip to content

Instantly share code, notes, and snippets.

@xleon
Last active August 29, 2015 14:15
Show Gist options
  • Save xleon/61781514c3dfb619b1a7 to your computer and use it in GitHub Desktop.
Save xleon/61781514c3dfb619b1a7 to your computer and use it in GitHub Desktop.
Entity framework nested collection filtering
public async Task<IEnumerable<Conversation>> GetUserConversations(string userId)
{
var temp = await conversationRepo.GetDbSet()
.Where(x => x.DeletedBy != userId)
.Where(x => x.SellerId == userId || x.BuyerId == userId)
.Select(x => new
{
conversation = x,
buyer = x.Buyer,
seller = x.Seller,
ad = x.Ad,
images = x.Ad.Images,
messages = x.Messages
.OrderByDescending(m => m.SentAt)
.Take(AppConstants.CHAT_PAGE_SIZE)
.OrderBy(m => m.SentAt),
newMessagesCount = x.Messages.Where(m => !m.Read && m.SenderId != userId).Count()
}).ToListAsync();
IEnumerable<Conversation> conversations = temp
.Select(x =>
{
var conversation = x.conversation;
conversation.NewMessagesCount = x.newMessagesCount;
return conversation;
})
.OrderByDescending(x => x.Messages.LastOrDefault().SentAt)
.ToList<Conversation>();
return conversations;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment