Lesson 80 of 93 · 6 min read · Updated
Testing Real DbContext Behaviour: Query Translation, Transactions and Change Tracking
On this page
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
- .NET 11 SDK
- xUnit 2.9.3
Microsoft.EntityFrameworkCore.Sqlite11.0.0- FluentAssertions 7.2.2
- 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
The test runs the same shape of query against SQLite:
M09.IntegrationApi.Tests/EfCoreProviderTests.cs
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
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
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
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
- Run queries against a relational provider so LINQ-to-SQL translation failures show up in tests.
EF.Functions.Likecase sensitivity depends on the provider: SQLite ignores ASCII case, PostgreSQL does not.- Some comparisons, such as
DateTimeOffseton SQLite, need a value converter before they can run in SQL. - Test transactions against a provider that supports them, and call
ChangeTracker.Clear()before asserting on database state. AsNoTrackingis observable behaviour; test it if your code depends on it.