When does the Entity Framework execute the query of a Iqueryable?

Asked

Viewed 498 times

13

I am developing a method for an API that consists of the following: fetching all customer reviews and, if specified, limiting 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 here was this: to do var query = *consulta* I’d just be creating to query, which will only be implemented later (with ToList() or, in this case, when returning the data).

Is that right or the query is executed at that first moment of the example?

  • 1

    Related (en): http://stackoverflow.com/q/2678405/4190610

1 answer

12


In short, at the moment it is IQueryable is converted to IEnumerable.

Detailing a little more, the following methods trigger this conversion:

See some more of the methods here.

And these do not provoke such conversion:

See all methods here.

Is that right or the query is executed at that first moment of the example?

No. She’s executed here:

return query;

In case, you are converting something that is IQueryable in IEnumerable. By the way, if you change the type of return to IQueryable, to query would not be executed.

His reasoning of postponing 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(...);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.