Search code examples
asp.net-core-webapiasp.net-core-2.2

Query data inside collection


I am trying to query firms which have category which categoryId field equals my parameter. Here is my code:

These are my models:

public class Firm
{
    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection<FirmCategory> Categories { get; set; }
}

public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection<FirmCategory> Firms { get; set; }
}

public class FirmCategory
{
    public int FirmId { get; set; }
    public Firm Firm { get; set; }
    public int CategoryId { get; set; }
    public Category Category { get; set; }
}

I would like to do something like this:

var firms =  _context.Firms
    .Include(x => x.Categories)
        .ThenInclude(x => x.Category)
    .AsQueryable();
firms = firms.Where(x => x.Category.CategoryId == param.CategoryId)

I know this doesn't work but this is what I would like to achieve with either AsQueryable() or with ToList()

Thank you!


Solution

  • I fixed my problem by using these commands:

    var firms = _context.Firms.AsQueryable();
    
    firms = firms
                    .SelectMany(x => x.Categories)
                    .Where(x => x.CategoryId == param.CategoryId)
                    .Select(x => x.Firm)
                    .Include(x => x.Categories).ThenInclude(x => x.Category)
                    .Include(x => x.Services).ThenInclude(x => x.Service);
                    ;