在Entity Framework Core中使用动态过滤器

编程入门 行业动态 更新时间:2024-10-26 08:22:10
本文介绍了在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中使用动态过滤器

本文发布于:2023-11-15 05:51:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1591714.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:过滤器   动态   Entity   Framework   Core

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!