简体   繁体   中英

Filter navigation property EF core

In my repository I try to filter the products with the variants active but I do not know how because is first time. I should return all products with or without variants active

public async Task<IEnumerable<Articolo>> GetArticoliByDivisioneAsync(string divisione)
{
    return await _ctx.Articoli
                     .Where(a => a.Divisione == divisione
                                 && a.Category!= "001")
                     .Include(i => i.Varianti)
                     .Include(i => i.FotoArticoli)               
                     .ToListAsync();
}

The field I want to filter on is in Varianti .

How can do .Where(v => v.Active == 1) ?

Just add your filter to where Method

public async Task<IEnumerable<Articolo>> GetArticoliByDivisioneAsync(string divisione)
{
    return await _ctx.Articoli
        .Where(a => a.Divisione == divisione
                  && a.Category!= "001"
                  && a.Varianti.Any(v=>v.Active == 1))
        .Include(i => i.Varianti)
        .Include(i => i.FotoArticoli)               
        .ToListAsync();
}

if you don't need the value of Varianti you can remove include part

public async Task<IEnumerable<Articolo>> GetArticoliByDivisioneAsync(string divisione)
{
    return await _ctx.Articoli
        .Where(a => a.Divisione == divisione
                  && a.Category!= "001"
                  && a.Varianti.Any(v=>v.Active == 1))
        .Include(i => i.FotoArticoli)               
        .ToListAsync();
}

Add to Where() clause and use Any() :

return await _ctx.Articoli
        .Include(i => i.Varianti)
        .Include(i => i.FotoArticoli)
        .Where(a => a.Divisione == divisione
                  && a.Category!= "001"
                  && a => a.Varianti.Any(v => v.Active == 1))

        .ToListAsync();

To get all products with active variants need to make a projection to new article object and there filter variants

This is the solution

public async Task<IEnumerable<Articolo>> GetArticoliByDivisioneAsync(string divisione)
{
    return await _ctx.Articoli
                     .Where(a => a.Divisione == divisione
                                 && a.Category!= "001")
                     .Include(i => i.Varianti)
                     .Include(i => i.FotoArticoli)               
                     .Select(x => new Articolo
                    {
                        Codice = x.Codice ,
                        Prezzo = x.Prezzo ,
                        Varianti = x.Varianti.Where(v => v.attivo== 0).ToList(),
                        FotoArticoli = x.FotoArticoli
                    })           
                .ToListAsync();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM