[英]Entity Framework Core - dynamic filtering
I'm having an issue retrieving correct result from database using Entity Framework Core. 我在使用Entity Framework Core从数据库检索正确的结果时遇到问题。
Here is my Article
table: 这是我的
Article
表:
I would like to create dynamic filter using IQueryable
that will return the following results: 我想使用
IQueryable
创建动态过滤器,该过滤器将返回以下结果:
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: 返回:
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: 执行此代码后,我得到以下信息:
I get 3 articles as a result instead of 2 (Article Id's: 2,3,2). 结果是3篇文章,而不是2篇(文章ID:2、3、2)。
Any idea what I'm doing wrong? 知道我在做什么错吗?
I dont know what your WhereIf()
method do or what your really get from GetAll()
but if I replace WhereIf()
by Where()
it works as expected. 我不知道您的
WhereIf()
方法做什么,或者您实际上从GetAll()
获得什么,但是如果我将WhereIf()
替换为Where()
它将按预期工作。
private IQueryable<Article> FilteredByBrand(IQueryable<Article> articles, List<int> items)
{
return items.IsNullOrEmpty() ? articles : articles.Where(x => items.Contains(x.BrandId));
}
private IQueryable<Article> FilteredByGender(IQueryable<Article> articles, List<int> items)
{
return items.IsNullOrEmpty() ? articles : articles.Where(x => items.Contains(x.GenderId));
}
Returns 退货
2 - Cool t-shirt - 2 - 1
2-酷T恤-2-1
3 - Yellow panties - 3 - 13-黄色内裤-3-1
With EF Core, try this. 使用EF Core,请尝试此操作。
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.