实体框架核心-动态过滤 [英] Entity Framework Core - dynamic filtering
本文介绍了实体框架核心-动态过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在使用Entity Framework Core从数据库检索正确的结果时遇到问题。
I'm having an issue retrieving correct result from database using Entity Framework Core.
这是我的 Article
表:
< a href = https://i.stack.imgur.com/GCToi.jpg rel = nofollow noreferrer>
我想使用 IQueryable
创建动态过滤器,返回以下结果:
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)
返回:
这是我的控制器操作:
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:
我得到的结果是3篇文章,而不是2篇(文章ID: 2,3,2)。
I get 3 articles as a result instead of 2 (Article Id's: 2,3,2).
知道我在做什么错吗?
推荐答案
简单高效的动态过滤器
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;
}
}
这篇关于实体框架核心-动态过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文