DEV Community

Cover image for 3 LINQ Mistakes That Hurt Backend API Performance in .NET
Ayman Atif
Ayman Atif

Posted on

3 LINQ Mistakes That Hurt Backend API Performance in .NET

LINQ looks clean and harmless in C#.

But in real backend APIs, small mistakes can quietly turn into serious performance issues.

Here are 3 I’ve seen (and made) while working with .NET and Entity Framework:

1. Loading entire tables into memory

A common mistake is doing this:

var orders = dbContext.Orders.ToList();

var recent = orders.Where(o => o.CreatedAt > DateTime.UtcNow.AddDays(-7));

This pulls everything into memory first, then filters in C#.

The problem:

  • unnecessary memory usage
  • slow processing on large datasets
  • wasted database optimization

Fix:

Let the database do the work:

var recent = dbContext.Orders
.Where(o => o.CreatedAt > DateTime.UtcNow.AddDays(-7))
.ToList();

2. Hidden multiple database calls

LINQ queries can be deceptively reused:

var query = dbContext.Orders.Where(o => o.Total > 100);

var count = query.Count();
var list = query.ToList();

This can result in multiple database executions depending on how it's used.

Fix:

Materialize once:

var list = dbContext.Orders
.Where(o => o.Total > 100)
.ToList();

var count = list.Count;

3. Fetching more data than needed

Another common issue:

var orders = dbContext.Orders.ToList();

var result = orders.Select(o => new
{
o.Id,
o.CustomerName
});

You are still loading full rows from the database even though you only need 2 fields.

Fix:

Project early:

var result = dbContext.Orders
.Select(o => new
{
o.Id,
o.CustomerName
})
.ToList();

Key idea

LINQ itself is not the problem.

The real issue is where the execution happens:

  • in memory
  • or in the database

In backend systems, that difference matters a lot.

Closing thought

Most performance issues in APIs are not “big architecture problems”.

They start with small LINQ decisions like these.

Top comments (0)