Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF LINQ select entities where Id is in List

I was trying to select a list of entities using EF and Linq and I should retrieve only those that has a specific AccountId inside the Participants ICollection

public class Conversation
{
    public Conversation()
    {
        Participants = new List<Account>();
        Messages = new List<Message>();
    }

    [Key]
    public Int32 conversationId { get; set; }
    public ICollection<Message> Messages { get; set; }
    public ICollection<Account> Participants { get; set; }
}

_Db is DbContext

public async Task<List<Conversation>> FindByAccountIdAsync(Int32 id)
{
   return await _Db.Conversations.Where(....).ToListAsync(); 
   // .... select conversations where id == AccountId inside ICollection<Account> Participants
}

I have no idea on how to compose the query in LINQ

like image 873
Gavello Avatar asked Nov 22 '25 02:11

Gavello


1 Answers

Use Any:

return await _Db.Conversations
    .Where(c => c.Participants.Any(p => p.Id == id))
    .AsQueryable()
    .ToListAsync();
like image 181
DavidG Avatar answered Nov 24 '25 12:11

DavidG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!