At what point does the Entity Framework query an IQueryable?

12

I'm developing a method for an API that consists of the following: fetch all evaluations from a given client and, if specified, limit the amount of records that will be returned.

For example:

public IEnumerable<Avaliacao> GetAvaliacoes(int idCliente, [FromUri]uint limit = 0)
{
    var query = contexto.Avaliacoes.Include(x => x.Notas)
                              .Where(a => a.IdCliente == idCliente)
                              .OrderByDescending(x => x.DataRegistro);

    if (limit != 0)
       return query.Take((int)limit);

    return query;
}

What I thought of here was this: When doing var query = *consulta* I would only be creating the query , which will only be executed later (with ToList() or, in this case, when returning the data).

Is that right, or does the query run in that first instance of the example?

    
asked by anonymous 16.02.2016 / 21:50

1 answer

11

In summary, at the time it is IQueryable is converted to IEnumerable .

For a little more detail, the following methods cause this conversion:

See some more of the methods here .

And these do not cause this conversion:

See all methods here .

  

Is this correct, or does the query run at that first point in the example?

No. It runs here:

return query;

In this case, you are converting something that is IQueryable to IEnumerable . Incidentally, if you changed the return type to IQueryable , the query would not execute.

Your reasoning to postpone the production of the enumeration is right, so much so that there is no problem in doing the following:

var query = db.Entidades.Where(...);
query = query.Where(...);
if (condicao) query = query.Where(...);
    
16.02.2016 / 21:56