c# - 动态 Linq 不起作用 - 选择未应用

标签 c# linq dynamic asp.net-web-api iqueryable

我尝试了几种可能性,并对 stackoverflow 上的博客和答案进行了适当的研究。可能是我,但我就是无法让这个动态 linq 查询工作。

我在 Web Api 项目上有一个 Controller ,定义了以下投影和路线。

private static readonly Expression<Func<Company, CompanyLightListDTO>> AsCompanyLightListDTO = x => new CompanyLightListDTO
{
  Name = x.Name,
  Id = x.Id
};

[Route("Test")]
[ResponseType(typeof(CompanyLightListDTO))]
public IQueryable<CompanyLightListDTO> GetTest(string name=null, string 
email=null, bool? isSupplier=null, bool? isCustomer=null)
{
  IQueryable<Company> query = db.Companies;
  if (!String.IsNullOrEmpty(name))
    query.Where(c => c.Name.Contains(name));

  if (!String.IsNullOrEmpty(email))
    query.Where(c => c.Email.Contains(email));

  if (isSupplier.HasValue)
    query.Where(c => c.isSupplier.Equals(isSupplier));

  if (isCustomer.HasValue)
    query.Where(c => c.isCustomer.Equals(isCustomer));

  // Return ??
}

我已经尝试过多次返回。它们都忽略前面的所有 where.() 并返回所有公司。

not working because return all companies. The Where clauses are not applied

return query.Include(c => c.Name).Select(AsCompanyLightListDTO);
return query.Select(AsCompanyLightListDTO);

我唯一能让这个方法发挥作用的就是这样做

return db.Companies.Include(c => c.Name)
  .Where(c => c.Name.Contains(name)
    && c.Email.Contains(email)
    && c.isSupplier.Equals(isSupplier)
    && c.isCustomer.Equals(isCustomer))
  .Select(AsCompanyLightListDTO);

但我想要一个动态 linq 查询,以便我可以执行这些类型的调用:

api/Companies/Test/name=somename&isCustomer=True api/Companies/Test/isCustomer=True&isSupplier=True api/Companies/Test/name=somename&email=someemail

有任何高尚的开发人员愿意帮助新的编码员吗?

最诚挚的问候 德威尔逊

最佳答案

您是否尝试将 GetTest 替换为此?

IQueryable<Company> query = db.Companies;
if (!String.IsNullOrEmpty(name))
    query = query.Where(c => c.Name.Contains(name));

if (!String.IsNullOrEmpty(email))
    query = query.Where(c => c.Email.Contains(email));

if (isSupplier.HasValue)
    query = query.Where(c => c.isSupplier.Equals(isSupplier));

if (isCustomer.HasValue)
    query = query.Where(c => c.isCustomer.Equals(isCustomer));

Queryable 方法(SelectWhere 等)返回新的 IQueryable 实例。

关于c# - 动态 Linq 不起作用 - 选择未应用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36017834/

相关文章:

testing - 点击动态生成的几个链接部分

C# FolderBrowserDialog RootFolder "Mycomputer"在 Windows 10 上无法运行

c# - 如何在 join linq 语法中比较 null

c# - 如何忽略特定的 LINQ where 子句?

javascript - javascript中是否有任何方法/方式可以动态地将子节点添加到列表元素?

javascript - 为什么我的增量器返回一个对象? id_[对象 HTMLInputElement]

c# - Uri ToString() 方法解码 Uri 查询

c# - 为什么 VisualTreeHelper.GetChildrenCount() 为 Popup 返回 0?

c# - 使用 Rhino.Mocks stub 属性 setter 以在调用时执行操作?

C# 根据多个条件过滤列表中的项目