代码之家  ›  专栏  ›  技术社区  ›  Ben Hoffman

如果要检查的值为空,是否有添加或删除Linq to DB查询行的方法?

  •  2
  • Ben Hoffman  · 技术社区  · 15 年前

    如果我有这样的问题:

    String Category = HttpContext.Current.Request.QueryString["Product"].ToString();
    
    IQueryable<ItemFile> pressReleases = from file in connection.ItemFile
                                                               where file.Type_ID == 8
                                                                    && file.Category == Category 
                                                               select file;
    

    有没有一种方法可以使这个LINQ查询不使用该行 file.Category == Category 类别是空的还是空的?

    2 回复  |  直到 15 年前
        1
  •  3
  •   Marc Gravell    15 年前

    别再加了怎么样 where 除非你需要?

    IQueryable<ItemFile> pressReleases = from file in connection.ItemFile
                                         where file.Type_ID == 8
                                         select file;
    
    if(!string.IsNullOrEmpty(Category)) {
        pressReleases = pressReleases.Where(file => file.Category == Category);
    }
    

    这是因为LINQ查询可以用延迟的执行组合,所以这个过滤器仍然是最终TSQL的一部分。

        2
  •  2
  •   Sani Huttunen    15 年前

    这可能不是您想要的,但会产生相同的结果:

    String Category = HttpContext.Current.Request.QueryString["Product"].ToString();
    
    IQueryable<ItemFile> pressReleases = from file in connection.ItemFile
                                         where file.Type_ID == 8
                                         && (string.IsNullOrEmpty(Category) || file.Category == Category)
                                         select file;