【问题标题】:Dynamic linq query with dynamic where conditions and from conditions具有动态 where 条件和 from 条件的动态 linq 查询
【发布时间】:2013-01-27 16:06:30
【问题描述】:
public GetApplicants(string Office,
                         int Id,
                         List<int> cfrparts,
                         List<int> expertiseAreaIds,
                         List<int> authIds,
                         List<int> specIds)
    {
        bool isAuthIdsNull = authIds == null;
        authIds = authIds ?? new List<int>();
        bool isSpecIdNull = specIds == null;

enter code here
     var query =
            from application in Apps
            from cfr in application.cfr
            from exp in cfr.Aoe
           from auth in exp.Auth
            from spec in exp.Special

            where application.Design.Id == 14
            where  (iscfrpart || cfrPartIds.Contains(cfr.CfrP.Id))
            where (isexp || expertiseAreaIds.Contains(exp.Aoe.Id))
            where (isAuthIdsNull || authIds.Contains(auth.Auth.Id))
            where  (isSpecIdNull || specIds.Contains(spec.Special.Id))
            where application.Office.Text.Contains(Office)
            where application.D.Id == Id

            select application.Id;

如何使这个查询动态化。如果我只有 Id 和 Office 值,它仍然应该根据可用值给我结果集。目前它没有给我结果。

【问题讨论】:

    标签: linq entity-framework ef-code-first


    【解决方案1】:

    不要多次调用where,而是使用&amp;&amp;

     var query =
            from Apps
            where (iscfrpart || cfrPartIds.Contains(Apps.cfr.CfrP.Id))
            && (isexp || expertiseAreaIds.Contains(Apps.cfr.Aoe.Id))
            && (isAuthIdsNull || authIds.Contains(Apps.cfr.Aoe.Auth.Id))
            && (isSpecIdNull || specIds.Contains(Apps.cfr.Aoe.Special.Id))
            && Apps.Office.Text.Contains(Office)
            && Apps.D.Id == Id
    
            select application.Id;
    

    此外,如果传入的 Id 不等于 14,则此子句 application.D.Id == 14 将导致 0 个结果:application.D.Id == Id。您可能需要删除第一个子句。

    编辑:更新了您的 from 子句,但我仍然认为这不会起作用,因为您的表结构似乎关闭了。

    【讨论】:

    • 您好,谢谢您的回复。我已经进行了请求的更改,但如果 cfrIds、expertiseareaIds、authIds、specIds 为空,我仍然没有得到任何结果。如果其他人为空,我希望查询基于 designId、office、Id 提取数据。
    • 我刚刚注意到你的 from 声明完全搞砸了。让我更新答案。
    【解决方案2】:

    解决此问题不需要动态查询。您可以编写构造查询的代码。

    根据您拥有的信息创建一个构造过滤器的方法。

    public Expression<Func<Application, bool>> GetFilterForCFR(List<int> cfrParts)
    {
      if (cfrParts == null || !cfrParts.Any())
      {
        return app => true;
      }
      else
      {
        return app => app.cfr.Any(cfr => cfrParts.Contains(cfr.cfrPId));
      }
    }
    

    然后,您可以使用表达式构造查询。

    var query = Apps;
    var cfrFilter = GetFilterForCFR(cfrParts);
    query = query.Where(cfrFilter);
    
    //TODO apply the other filters
    
    var finalquery = query.Select(app => app.Id);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-30
      • 1970-01-01
      • 2012-12-24
      • 2019-03-28
      • 2011-09-21
      • 1970-01-01
      • 2016-07-27
      • 2015-01-30
      相关资源
      最近更新 更多