Kimmax
Kimmax

Reputation: 1697

IQueryable does not append WHERE statement in SQL

I'm using the EF6 with a MySQL server. I'm trying to dynamically append WHERE clauses based on the variable being null or not.
This is my code:

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() };
}

However the data is not being filtered by the WHERE clause and all rows from the table are being returned. Also in the MySQL log I see the statement which does not include a WHERE clause:

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

Am I using the IQueryable wrong?

Upvotes: 1

Views: 455

Answers (1)

ocuenca
ocuenca

Reputation: 39376

You need to save your query when you call Where method:

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())); 
//...

Upvotes: 6

Related Questions