我正在开发使用Entity Framework Core的应用程序(.Net Core 3.1,C#8).
I'm developing an application (.Net Core 3.1, C# 8) that is using Entity Framework Core.
我想用几个过滤选项过滤一个表.
I would like to filter a table with several filtering options.
我正在JSON中获取过滤条件,并将其反序列化为对象.我想写一个LINQ where查询,它将基于那些动态过滤选项来过滤表.
I'm getting the filter conditions in JSON and I'm deserializing it into an object. I want to write a where LINQ query which will filter the table based on those dynamic filtering options.
问题在于我需要使用许多选项和组合来管理过滤.
The twist is I need to manage the filtering with many options and combinations.
- 您可以过滤 market , country , vendor ,其余过滤选项将为 null .
- 您想过滤国家和供应商,然后 market 将为 null ,其余过滤器选项.
- You can filter for the market, country, vendor and the rest of the filter options will be null.
- You would like to filter for country and vendor then the market will be null and also the rest of the filter options.
我正在查询一个巨大的表,因此编写一个可以完全转换为SQL的查询非常重要.
I'm querying a huge table, so it is important to write a query which translates fully into SQL.
以下代码无法正常工作.我正在寻找可以解决此问题的类似方法:
The following code is not working properly. I'm looking for something similar that can solve this issue:
var filters = new demoFilterEntity() { Market = new List<string>() { "LAT", "NAM" } }; var filteredData = demoMainRepository.GetAll().Where(x => x.Market != null && (filters.Market != null ? filters.Market.Contains(x.Market) : false) && x.Country != null && (filters.Country != null ? filters.Country.Contains(x.Market) : false)).ToList();我希望您能提出一些建议,以解决这些问题并动态管理过滤.
I would appreciate suggestions on how I can get through this and manage the filtering dynamically.
推荐答案如果只有 AND 条件,则只需链接 Where 子句即可完成:
If you have only AND conditions you can do it with just chaining Where clauses:
var query = demoMainRepository.GetAll().Where(x => x.Market != null); if(filters.Market != null) { query = query.Where(x => filters.Market.Contains(x.Market)); } ... var filteredData = query.ToList();@Lajos Arpad 也说过,也许您需要考虑合并字段空检查(即 x.Market!= null ),并进行过滤器检查:
Also as @Lajos Arpad said maybe you need to consider combining fields null checks (i.e. x.Market != null) with the filters checks:
var query = demoMainRepository.GetAll(); if(filters.Market != null) { query = query.Where(x => x.Market != null && filters.Market.Contains(x.Market)); } ... var filteredData = query.ToList();更多推荐
在Entity Framework Core中使用动态过滤器
发布评论