Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

134
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda