I'm trying to optimize the following routine so that it only uses one database query instead of multiple but the filter (loop conditions) don't seem to be applied as all messeges are fetched.
public async Task<List<Message>> GetInboxMessegesFromUser(string inboxUser, List<string> senders)
{
// Doesn't work
var query = from m in _context.Messeges where m.ToUser == inboxUser select m;
foreach (string sender in senders)
{
query.Where(m => m.FromUser == sender);
}
return await query.ToListAsync();
// Old code
List<Message> messeges = new List<Message>();
foreach (string sender in senders)
{
messeges.AddRange(await _context.Messeges.Where(m => m.FromUser == sender && m.ToUser == inboxUser).ToListAsync());
}
return messeges;
}
How to add a dynamic number of conditions to a LINQ query before executing it so that a O(N*M) turns into O(N) ?
query = query.Where(m => m.FromUser == sender);query = query.Where(....);. You cant have a record that has more than 1 value on a property. So if you pass in 2 values in thesendersList any one record will never be both of those values. The result is that this method will always return an empty list.