LINQ and EF Core in High-Performance Environments: Architecture at Scale

Automated English translation of the original Spanish article. Code examples keep their original identifiers.

In our previous articles, we laid the groundwork for writing elegant code with LINQ and broke down how to master advanced joins. We also raised the red flags on why applications struggle when handling millions of records.

When your dataset scales from thousands to millions of rows, writing queries that simply “work” is no longer enough. You need to understand precisely how .NET internals operate and how the ORM interacts with the database engine. In this advanced guide, we’ll connect these concepts to build a data architecture that won’t collapse under pressure.

1. From Manual Joins to Efficient Navigation Properties

In our article on Joins, we learned how to couple tables explicitly using the join … on … equals syntax. In Entity Framework Core, the best practice is to abstract these joins by leveraging navigation properties configured on your entities.

When you execute a projection using navigation properties, the LINQ provider automatically translates the expression tree into the appropriate SQL join clauses:

// Proyección directa optimizada que genera un JOIN automático en el servidor
var reporte = await _context.Empleados
    .Select(e => new { e.Nombre, e.Departamento.NombreDepartamento })
    .AsNoTracking() // Desactiva el Change Tracker (Ahorro O(n) en memoria)
    .ToListAsync();

By skipping manual joins, you reduce the likelihood of syntax mistakes and allow EF Core’s query optimizer to evaluate the best join strategy based on the model’s foreign keys.

2. Pagination at Scale: The End of Traditional .Skip() and .Take()

A widespread anti-pattern when paginating large tables is the use of deep offsets. The code .Skip(500000).Take(50) forces the database engine (SQL Server, PostgreSQL) to scan the first 500,000 index rows only to discard them and return the requested 50. Even with a sorted index, this traversal requires an expensive Index Scan that severely degrades performance and increases read contention as offsets grow.

The architectural alternative is Keyset pagination (the Seek Method), which applies a filter condition based on the primary key of the last processed record:

// Paginación eficiente que aprovecha los índices B-Tree
var paginaSiguiente = await _context.Orders
    .Where(o => o.Id > lastProcessedOrderId) // Filtro directo sobre índice
    .OrderBy(o => o.Id)
    .Take(50)
    .AsNoTracking()
    .ToListAsync();

This technique brings search complexity down to constant O(log N) time, ensuring that the query takes the exact same milliseconds on the first page as it does on page ten thousand.

3. Avoiding Cartesian Explosion with Split Queries

Once we move away from manual joins and adopt navigation properties, it is common to use .Include() to load related collections (Eager Loading). However, including multiple one-to-many relationships within a single LINQ statement generates a massive Cartesian product in SQL.

// Riesgo de explosión cartesiana: multiplica filas innecesariamente
var datosComplejos = await _context.Departamentos
    .Include(d => d.Empleados)
    .Include(d => d.Proyectos)
    .ToListAsync();

If a department has 100 employees and 30 projects, the SQL server will transmit 100 × 30 = 3,000 redundant rows over the network for every single department. To solve this without reverting to cumbersome manual joins, we instruct the ORM to intelligently split the load using AsSplitQuery():

// Optimización mediante consultas divididas coordinadas
var datosOptimizados = await _context.Departamentos
    .Include(d => d.Empleados)
    .Include(d => d.Proyectos)
    .AsSplitQuery() // Genera comandos SQL independientes pero vinculados
    .ToListAsync();

4. The Technical Boundary: Expression Trees vs. Delegates

To diagnose why certain queries fail at runtime with an InvalidOperationException, it is essential to understand the boundary separating IQueryable from IEnumerable:

  • IQueryable operates on Expression Trees (Expression<Func<T, ...>>): The written code is not executed directly in C#. EF Core receives a hierarchical data structure (a tree of expression nodes), and a query provider (IQueryProvider) analyzes that structure to translate it into valid T-SQL or PL/SQL statements. If you include C# methods not mapped by the provider, translation will fail.
  • IEnumerable operates on Compiled Delegates (Func<T, ...>): Execution happens strictly in the application server’s memory over already instantiated native C# objects.

Therefore, bulk data mutation operations should be delegated entirely to the database server using direct execution commands like ExecuteUpdateAsync or ExecuteDeleteAsync, bypassing entity loading and in-memory change tracking altogether:

// Ejecución directa en base de datos: Cero impacto en el Change Tracker y el Heap de .NET
await _context.Logs
    .Where(l => l.Timestamp < limiteFecha && !l.Procesado)
    .ExecuteUpdateAsync(s => s.SetProperty(l => l.Procesado, true));

This distinction doesn’t just matter for mutations: it also defines the boundary between what is processed efficiently on the database server and what, once materialized into memory, can become a source of pressure on the .NET runtime.

5. The Low-Level Impact: Closures and Garbage Collector Pressure

When a query has already been materialized and we work with in-memory collections (IEnumerable / LINQ to Objects), careless use of lambda expressions inside loops can trigger severe Heap allocation issues due to variable capture, or Closures.

// Problema latente de asignación de memoria a corto plazo
foreach (var codigo in codigosPostales)
{
    var filtrados = listaEnMemoria.Where(e => e.CodigoPostal == codigo).ToList();
}

Because the lambda expression needs to evaluate the iterator variable codigo, which resides outside its local scope, the C# compiler is forced to instantiate a hidden class (a display class) on the Heap to capture that variable’s state across every iteration.

In high-concurrency applications or global APIs, this massive, repeated allocation rapidly fills Generation 0 memory, forcing the Garbage Collector to trigger Stop-the-World pauses to clean up ephemeral objects. In performance-critical hot paths, the solution is to migrate these declarative queries to indexed imperative loops that eliminate secondary allocations:

// Alternativa imperativa: sin closures, sin asignaciones en el Heap por iteración
var resultado = new List<Empleado>();

for (int i = 0; i < listaEnMemoria.Count; i++)
{
    if (listaEnMemoria[i].CodigoPostal == codigosPostales[codigoIdx])
        resultado.Add(listaEnMemoria[i]);
}

By accessing elements directly by index and comparing values within the loop’s local scope, the compiler has no external variables to capture, completely eliminating display class allocations.

When to Delegate and When to Intervene

Entity Framework Core and LINQ offer a robust ecosystem built for high productivity. The key to keeping applications stable when handling millions of records lies in knowing when to leverage the ORM’s level of abstraction (via navigation properties and deferred parameterized queries) and when to intervene directly at the infrastructure level using split queries, keyset pagination, or native bulk operations.

Clean code isn’t just code that is easy to read—it’s code that respects memory, CPU, and network bandwidth on the hardware running it.