IQueryable不会在SQL

时间:2016-01-18 17:44:57

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

我将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错了吗?

1 个答案:

答案 0 :(得分:6)

您需要在调用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())); 
//...
相关问题