Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

133
Vistas
Does the for loop invocation result in fetching all records from the database and is there a way to control this behaviour?
using (AdventureWorksEntities context = new AdventureWorksEntities())
{
    var query = context.Products
        .Select(product => new
        {
            ProductId = product.ProductID,
            ProductName = product.Name
        });

    Console.WriteLine("Product Info:");
    foreach (var productInfo in query)
    {
        Console.WriteLine("Product Id: {0} Product name: {1} ",
            productInfo.ProductId, productInfo.ProductName);
    }
}

I understand that the query gets executed on the database server when the for loop starts executing. Assuming the database server returns the entire result back to the .net application and the entire data is held in query variable.

Is there any way to limit this so as to prevent memory overflow issues.

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

As stated here, using foreach directly on an EF IQueryable streams the data, loading each entity into memory individually.

This reduces memory consumption, with the caveat that the underlying table(s) will be locked for the duration of the loop execution.

Note that as highlighted by David in the comments, you should also disable tracking to make entities eligible for garbage collection after each iteration.

Thais can be done for an individual query using AsNoTracking:

foreach (var productInfo in query.AsNoTracking())

Or globally using QueryTrackingBehavior.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda