Entity Framework Core - dynamic filtering

c# entity-framework-core filtering

Question

I'm having an issue retrieving correct result from database using Entity Framework Core.

Here is my Article table:

enter image description here

I would like to create dynamic filter using IQueryable that will return the following results:

Select a.Id, a.Name, a.BrandId, a.GenderId
from dbo.Articles a
where GenderId in (1)
  and BrandId in (1, 2, 3)

which returns:

enter image description here

This is my controller action:

public async Task<IActionResult> Clothes()
{
    var model = new ArticleFilterViewModel();
    model.Genders.AddRange(new int[1] { 1 });
    model.Brands.AddRange(new int[3] { 1, 2, 3 });
    var result = await articleSerivce.GetFilteredUsers(model);
    return View(result);
}

Here is my repository method for fetching filtered articles:

public ICollection<Article> GetFilteredUsers(ArticleFilter filter)
{
    var articles = GetAll();
    articles = FilteredByBrand(articles, filter.Brands);
    articles = FilteredByGender(articles, filter.Genders);
    var result = articles.ToList();
    return result;
}

IQueryable<Article> FilteredByBrand(IQueryable<Article> articles,  List<int> items)
{
    return articles.WhereIf(items.IsNotNullOrEmpty(),  x => items.Contains(x.BrandId));
}

IQueryable<Article> FilteredByGender(IQueryable<Article> articles, List<int> items)
{
     return articles.WhereIf(items.IsNotNullOrEmpty(), x => items.Contains(x.GenderId));
}

After this code is executed I get the following:

enter image description here

I get 3 articles as a result instead of 2 (Article Id's: 2,3,2).

Any idea what I'm doing wrong?

1
0
8/23/2018 9:04:48 AM

Popular Answer

With EF Core, try this.

Simple and performatic dynamic filter

public static List<Inventory> GetAll(string po, string cod)
{
    using (var context = new ApplicationDbContext())
    {
        var Items = context.Inventorys
            .Where(p => p.CodigoPO == po || po == string.Empty)
            .Where(p => p.CodigoProduto == cod || cod == string.Empty).ToList();
        return Items;
    }
}

Generated by EF Core, using only the PO parameter Generated by EF Core, using only the PO parameter

1
2/8/2019 9:40:02 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow