Lesson 80 of 93 · 6 min read · Updated

Testing Real DbContext Behaviour: Query Translation, Transactions and Change Tracking

EF Core does a lot of work between your LINQ query and the rows that come back. It translates expressions to SQL, sends them to the database, tracks the entities it loads, and runs your writes inside transactions. A test that replaces the DbContext with a mock, or runs against the EF InMemory provider, skips most of that. This lesson shows three tests that run against a real relational provider (SQLite in-memory) and prove behaviour that only exists there.

Technical Requirements

  1. .NET 11 SDK
  2. xUnit 2.9.3
  3. Microsoft.EntityFrameworkCore.Sqlite 11.0.0
  4. FluentAssertions 7.2.2
  5. Docker is not required.

Exercising the Real Query Path

The Books API has a search endpoint that uses EF.Functions.Like. That method exists to be translated into a SQL LIKE, so its exact behaviour is defined by the database engine, not by .NET.

M09.IntegrationApi/Endpoints/BookEndpoints.cs

/// <summary>
/// Search: the best example of PROVIDER-DEPENDENT behaviour.
/// In SQLite, LIKE is case-insensitive for ASCII by default;
/// in PostgreSQL, LIKE is case-sensitive. That is why this behaviour must be
/// tested with the REAL provider — EF InMemory can never catch it.
/// </summary>
private static async Task<Ok<IReadOnlyList<BookResponse>>> SearchAsync(
string term, AppDbContext db, CancellationToken cancellationToken)
{
var books = await db.Books
.AsNoTracking()
.Where(b => EF.Functions.Like(b.Title, $"%{term}%"))
.OrderBy(b => b.Title)
.Select(b => new BookResponse(b.Id, b.Isbn, b.Title, b.Author, b.PriceTry, b.PublishedYear))
.ToListAsync(cancellationToken);

return TypedResults.Ok<IReadOnlyList<BookResponse>>(books);
}

The test runs the same shape of query against SQLite:

M09.IntegrationApi.Tests/EfCoreProviderTests.cs

[Fact]
public async Task SqliteProvider_ExecutesRealQueryTranslation()
{
// We run the real QUERY PATH.
// If the LINQ → SQL translation fails, the test breaks here;
// in InMemory the LINQ runs in memory, so the error NEVER shows up.
var (db, connection) = CreateSqliteContext();
await using var _ = db;
await using var __ = connection;

db.Books.AddRange(
NewBook("978-1", "Ada'nın Günlüğü"),
NewBook("978-2", "Kayıp Zaman"),
NewBook("978-3", "Zamanın Kısa Tarihi"));
await db.SaveChangesAsync();

var results = await db.Books
.Where(b => EF.Functions.Like(b.Title, "%zaman%"))
.OrderBy(b => b.Title)
.Select(b => b.Title)
.ToListAsync();

// In SQLite, LIKE is case-INSENSITIVE for ASCII characters.
// In PostgreSQL the same query would be case-sensitive → this is provider-dependent
// behaviour, and full fidelity needs the production database.
results.Should().Contain("Kayıp Zaman");
}

Two things are proven here. First, the query translates: if someone adds a method call EF Core cannot turn into SQL, ToListAsync throws an InvalidOperationException that says the expression "could not be translated", and the test fails. Without such a test, that exception appears for the first time when a user calls the endpoint. Second, the search pattern %zaman% (lower case) finds "Kayıp Zaman" (capital Z), because SQLite's LIKE ignores case for ASCII letters. That second fact is a property of the provider, not of your code. On PostgreSQL, LIKE is case-sensitive and the same query would return nothing. The test documents the behaviour you get today and tells you where the risk is if production uses a different engine.

Pitfall: Some Types Cannot Be Compared in SQL Without Help

Query translation also fails for reasons you would not expect. SQLite has no native DateTimeOffset type, so EF Core cannot translate a comparison such as r.ExpiresAtUtc <= now into SQL. The fix lives in the model:

M09.IntegrationApi/Data/AppDbContext.cs

modelBuilder.Entity<BookReservation>(entity =>
{
entity.HasKey(x => x.Id);
entity.Property(x => x.CustomerEmail).IsRequired().HasMaxLength(200);

// SQLite cannot translate a DateTimeOffset comparison (<=) into a query;
// stored as UTC ticks, the comparison runs in the database.
entity.Property(x => x.ExpiresAtUtc)
.HasConversion(v => v.UtcTicks, v => new DateTimeOffset(v, TimeSpan.Zero));
});

With the value stored as a long, the comparison becomes a plain integer comparison in SQL. You would only discover the need for this converter by running the query against a real relational provider. A mocked context or the InMemory provider would let the comparison run in memory and hide the problem. This is the general weakness of mocking DbContext or DbSet: the mock returns whatever you tell it to, so the test can never fail for a reason that lives in the database.

Transactions Are a Relational Reality

The next test opens a transaction, saves a row inside it, and rolls back.

M09.IntegrationApi.Tests/EfCoreProviderTests.cs

[Fact]
public async Task SqliteProvider_SupportsTransactionsAndRollback()
{
// Transaction behaviour is a relational reality; InMemory does not have it.
var (db, connection) = CreateSqliteContext();
await using var _ = db;
await using var __ = connection;

db.Books.Add(NewBook("978-KALICI"));
await db.SaveChangesAsync();

await using (var transaction = await db.Database.BeginTransactionAsync())
{
db.Books.Add(NewBook("978-GERI-ALINACAK"));
await db.SaveChangesAsync();

await transaction.RollbackAsync();
}

// Clear the change tracker and read the REAL state of the database.
db.ChangeTracker.Clear();

var isbns = await db.Books.Select(b => b.Isbn).ToListAsync();
isbns.Should().ContainSingle().Which.Should().Be("978-KALICI");
}

The first book is committed. The second is saved inside the transaction and then rolled back. After the rollback, only the first book exists in the database.

Note the db.ChangeTracker.Clear() call. Without it, the context still holds the rolled-back entity as Unchanged, because SaveChangesAsync succeeded before the rollback. The database no longer has that row, but the context does not know. Clearing the tracker makes the intent explicit: the assertion reads what is in the database, and no stale instance from the context can leak into later reads.

The EF InMemory provider cannot run this test meaningfully. By default it throws when you begin a transaction (the TransactionIgnoredWarning). If you suppress that warning, it ignores the transaction, the rollback does nothing, and both books stay.

Change Tracking Is Real Behaviour Too

The last test checks how AsNoTracking affects the change tracker:

M09.IntegrationApi.Tests/EfCoreProviderTests.cs

[Fact]
public async Task AsNoTracking_DoesNotAttachEntitiesToTheChangeTracker()
{
// Change tracking is also a REAL behaviour of EF.
var (db, connection) = CreateSqliteContext();
await using var _ = db;
await using var __ = connection;

db.Books.Add(NewBook("978-TAKIP"));
await db.SaveChangesAsync();
db.ChangeTracker.Clear();

var untracked = await db.Books.AsNoTracking().ToListAsync();
untracked.Should().ContainSingle();
db.ChangeTracker.Entries().Should().BeEmpty();

var tracked = await db.Books.ToListAsync();
tracked.Should().ContainSingle();
db.ChangeTracker.Entries().Should().ContainSingle();
}

The read endpoints in the API use AsNoTracking() because they never modify what they load. Tracking costs memory and CPU, and a tracked entity can be saved by accident if some later code calls SaveChangesAsync. This test pins down the behaviour those endpoints rely on. It also shows the contrast in one place: the same query without AsNoTracking attaches exactly one entry to the tracker.

Summary

  1. Run queries against a relational provider so LINQ-to-SQL translation failures show up in tests.
  2. EF.Functions.Like case sensitivity depends on the provider: SQLite ignores ASCII case, PostgreSQL does not.
  3. Some comparisons, such as DateTimeOffset on SQLite, need a value converter before they can run in SQL.
  4. Test transactions against a provider that supports them, and call ChangeTracker.Clear() before asserting on database state.
  5. AsNoTracking is observable behaviour; test it if your code depends on it.