【问题标题】:IQueryable does not append WHERE statement in SQLIQueryable 不在 SQL 中附加 WHERE 语句
【发布时间】:2016-04-23 23:43:38
【问题描述】:

我将 EF6 与 MySQL 服务器一起使用。我正在尝试根据变量是否为空来动态附加 WHERE 子句。
这是我的代码:

using (var dbContext = new Entities())
{
    IQueryable<Boxes> boxes = dbContext.Boxes;

    if(this.Customer != null)
        boxes.Where(box => box.CurrentCustomer == this.Customer);    

    if(this.IDs != null)
        boxes.Where(box => this.IDs.Split(',').Any(id => id == box.ID.ToString()));  

    return new Response() { Success = true, Result = boxes.ToList() };
}

但是,WHERE 子句没有过滤数据,并且正在返回表中的所有行。同样在 MySQL 日志中,我看到不包含 WHERE 子句的语句:

1994 Query SELECT
`Extent1`.`ID`,
`Extent1`.`CurrentCustomer`
FROM `Boxes` AS `Extent1`

我是不是用错了IQueryable

【问题讨论】:

  • 您确定this.Customerthis.Ids 不为空吗?
  • 在 Linq 中,.Where 实际上返回了一个结果。
  • 当然。做了一步步调试

标签: c# mysql entity-framework linq linq-to-entities


【解决方案1】:

调用Where方法时需要保存查询:

IQueryable<Boxes> boxes = dbContext.Boxes;

if(this.Customer != null)
   boxes= boxes.Where(box => box.CurrentCustomer == this.Customer);    

if(this.IDs != null)
    boxes=boxes.Where(box => this.IDs.Split(',').Any(id => id == box.ID.ToString())); 
//...

【讨论】:

  • 嗯.. 这将是我浪费时间的前 10 件事情:D 谢谢!
猜你喜欢
  • 2019-06-26
  • 2011-10-22
  • 1970-01-01
  • 2015-04-21
  • 1970-01-01
  • 1970-01-01
  • 2013-10-10
  • 1970-01-01
  • 2022-12-19
相关资源
最近更新 更多