在Entity Framework Core中使用动态过滤器 [英] Using dynamic filters with Entity Framework Core

查看:51
本文介绍了在Entity Framework Core中使用动态过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发使用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中使用动态过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆