loading experience

Guide

Guide to data, testing and performance in .NET: EF Core, xUnit and BenchmarkDotNet

Guide to data, testing and performance in .NET: EF Core, xUnit and BenchmarkDotNet

What is new in EF Core 10 and ten tips for faster queries, tests with xUnit v3 (unit and integration) and how to measure performance with BenchmarkDotNet: the guide to data, testing and measurement for .NET code.

In this guide

  1. EF Core 10: LeftJoin, named filters and vector search
  2. EF Core: ten tips for faster queries
  3. Testing in .NET with xUnit v3: unit and integration tests
  4. BenchmarkDotNet: measuring the performance of .NET code

EF Core 10: LeftJoin, named filters and vector search

Entity Framework Core 10 ships alongside .NET 10 as a long-term support release. Here are the new features that simplify everyday code the most.

Each filter has a name and can be disabled alone, leaving the others active.
Each filter has a name and can be disabled alone, leaving the others active.

LeftJoin and RightJoin

A left join in LINQ used to require an unreadable combination of GroupJoin, SelectMany and DefaultIfEmpty. Now there is a dedicated operator:

var rows = await db.Customers
    .LeftJoin(db.Orders,
        c => c.Id,
        o => o.CustomerId,
        (c, o) => new { c.Name, Total = o == null ? 0 : o.Total })
    .ToListAsync();

Named query filters

Global filters (for example "only non-deleted rows" or "only the current tenant") can now be more than one per entity and have a name, so you can disable just one of them:

modelBuilder.Entity<Document>()
    .HasQueryFilter("NotDeleted", d => !d.IsDeleted)
    .HasQueryFilter("Tenant", d => d.TenantId == _tenantId);

// recycle bin: include deleted rows, but still only for the current tenant
var bin = await db.Documents
    .IgnoreQueryFilters(["NotDeleted"])
    .Where(d => d.IsDeleted)
    .ToListAsync();

Vector search

With SQL Server 2025 and Azure SQL, EF Core 10 supports the vector type and the distance function: you can store embeddings generated by an AI model and find the most similar documents directly with LINQ, without a separate database. It is the foundation for semantic search and for systems that enrich a language model's answers with company documents.

Other improvements

  • Support for the native JSON type of recent SQL Server versions.
  • More flexible complex types, including optional ones and ones mapped to JSON columns.
  • ExecuteUpdateAsync is easier to compose with conditional logic.

EF Core: ten tips for faster queries

Entity Framework Core is productive, but a few habits can turn a fast page into a slow one. Here are the tips we apply in every project.

The same information, with far less work for the database.
The same information, with far less work for the database.

1. Read only what you need

var list = await db.Products
    .Where(p => p.IsActive)
    .Select(p => new ProductRow(p.Id, p.Name, p.Price))
    .ToListAsync();

2. AsNoTracking for reads

If you do not need to modify the entities, AsNoTracking() avoids the cost of the change tracker.

3. Watch out for the N+1 problem

Loading a list and then accessing a relationship inside a loop generates one query per row. Use Include or, better, a projection that brings the related data along.

4. Split queries for multiple collections

Including several collections in the same query multiplies the rows returned. AsSplitQuery() loads them with separate queries.

5. Always paginate in the database

var page = await db.Orders
    .OrderByDescending(o => o.Date)
    .Skip((number - 1) * size)
    .Take(size)
    .ToListAsync();

6. Bulk updates

await db.Sessions
    .Where(s => s.ExpiresAt < DateTime.UtcNow)
    .ExecuteDeleteAsync();

7-10. The other habits

  • Indexes on columns used in filters and sorting: no ORM makes up for a missing index.
  • Compiled queries for the most frequent queries.
  • DbContext pooling with AddDbContextPool in high-traffic applications.
  • Look at the generated SQL: ToQueryString() and command logging show what really reaches the database.

Testing in .NET with xUnit v3: unit and integration tests

Tests are the safety net that lets you upgrade frameworks and libraries without fear. xUnit v3 is the new generation of one of the most widely used test frameworks in .NET.

The lower you go, the more numerous, fast and cheap the tests are.
The lower you go, the more numerous, fast and cheap the tests are.

A unit test

public class DiscountTests
{
    [Theory]
    [InlineData(100, 0)]
    [InlineData(200, 10)]
    [InlineData(1000, 100)]
    public void Compute_ReturnsExpectedDiscount(decimal total, decimal expected)
    {
        var discount = DiscountCalculator.For(total);
        Assert.Equal(expected, discount);
    }
}

What is new in xUnit v3

  • Test projects are executables and run on Microsoft's new, lighter testing platform.
  • TestContext.Current gives access to the running test, including a CancellationToken that is cancelled if the test is stopped.
  • Dynamically skipped tests and better support for asynchronous tests.

Integration tests for APIs

WebApplicationFactory starts the whole ASP.NET Core application in memory: requests go through real middleware, routing and serialisation, without opening network ports.

public class ProductsApiTests(WebApplicationFactory<Program> factory)
    : IClassFixture<WebApplicationFactory<Program>>
{
    [Fact]
    public async Task GetProducts_ReturnsOk()
    {
        var client = factory.CreateClient();
        var response = await client.GetAsync("/api/products", TestContext.Current.CancellationToken);
        response.EnsureSuccessStatusCode();
    }
}

What to test

Business rules with many fast unit tests; the main API paths with integration tests; a few end-to-end tests for critical flows. A test that fails randomly must be fixed immediately: otherwise nobody will trust the suite any more.


BenchmarkDotNet: measuring the performance of .NET code

Measuring time with a Stopwatch in a loop gives numbers distorted by the JIT, caches and the garbage collector. BenchmarkDotNet handles warm-up, repetitions and statistics for you.

Warm-up and repetitions remove the noise that skews hand-made measurements.
Warm-up and repetitions remove the noise that skews hand-made measurements.

A complete benchmark

using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;

BenchmarkRunner.Run<ConcatBenchmark>();

[MemoryDiagnoser]
public class ConcatBenchmark
{
    [Params(10, 1000)]
    public int N;

    [Benchmark(Baseline = true)]
    public string WithPlus()
    {
        var s = "";
        for (var i = 0; i < N; i++) s += i;
        return s;
    }

    [Benchmark]
    public string WithStringBuilder()
    {
        var sb = new System.Text.StringBuilder();
        for (var i = 0; i < N; i++) sb.Append(i);
        return sb.ToString();
    }
}
dotnet run -c Release

Reading the results

  • Mean: average time per operation.
  • Error and StdDev: how stable the measurements are; if they are large, the result is unreliable.
  • Ratio: comparison with the method marked as baseline.
  • Allocated: memory allocated per operation, often more important than time.

Comparing .NET versions

The same benchmark can run on several runtimes, for example with the --runtimes net8.0 net10.0 command-line option: it is the most concrete way to evaluate an upgrade.

Golden rules

Always in Release configuration, never with a debugger attached, with realistic data and measuring what really matters to the user. Only optimise code that a profiler or a benchmark identifies as a bottleneck.


Comments (0)

No comments yet.

Leave a comment