【问题标题】:Linq chaining conditionsLinq 链接条件
【发布时间】:2021-01-27 08:38:38
【问题描述】:

需要根据输入对象的输入链接where 条件。在 EF 核心中使用 LINQ

例如:select * from employee where name = 'test' and place = 'us' 这两个条件总是存在的。此外,我还有 3 个可能有也可能没有的可选参数,例如:城市、县和邮编。

如果城市存在,则第一个条件检查仅将城市条件附加到现有的 where 条件。例如:select * from employee where name = 'test' and place = 'us' and city = 'ny' 并且查询只需要在数据库级别进行。

如果城市不存在,则检查县是否存在 例如:select * from employee where name = 'test' and place = 'us' and country = 'testcounty' 并且查询只需要在数据库级别进行。

如果县不存在检查 zip 如果存在例如:select * from employee where name = 'test' and place = 'us' and zip = '123' 并且查询只需要在数据库级别发生。

如果所有内容都不存在,则返回例如:select * from employee where name = 'test' and place = 'us' 并且查询只需要在数据库级别进行。

我通过应用条件名称和位置在 LINQ 中尝试了一些,稍后,使用 where 应用可选的必需值,但再次将所有这些值放入内存可能会影响性能检查是否有更好的方法来处理此请求。

谢谢

【问题讨论】:

    标签: entity-framework linq asp.net-core .net-core linq-to-sql


    【解决方案1】:

    您必须使用Concat 进行此类查询

    var baseQuery = from e in employee
      where e.name == "test" && e.place == "us" 
      select e;
    
    var byCity = from e in baseQuery
      where e.city == "ny"
      select e;
    
    var byCountry = from e in baseQuery
      where e.country == "testcounty"
      select e;
    
    var result = byCity
      .Concat(byCountry)
      .Concat(baseQuery)
      .FirstOrDefault();
    

    此查询的执行计划应通过 SQL Server 或其他现代数据库进行优化。

    【讨论】:

      猜你喜欢
      • 2010-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-07
      • 1970-01-01
      • 2011-12-07
      相关资源
      最近更新 更多