📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How do you test EF Core data access against a database? Compare the EF Core in-memory provider, SQLite and a real SQL Server in a container, and explain how you reset state between tests with Respawn or transactions.

Covers the options for database testing with EF Core (in-memory provider, SQLite, SQL Server via Testcontainers), their fidelity gaps, and resetting state with Respawn, transaction rollback or per-test databases.

Mid-Level Theory Intermediate database-testing ef-core respawn sql-server testcontainers testing

🎯 Key points

  • EF Core in-memory provider is not relational: no constraints, transactions or SQL translation; the EF Core testing docs recommend against it for testing data access
  • The in-memory provider can still be tolerable for trivial tests where no query or constraint is under test, but a repository fake is usually clearer
  • SQLite is relational but a different dialect: types, schemas, collation and some functions differ from SQL Server
  • SQL Server in a Testcontainers container gives production fidelity for queries, constraints and migrations
  • Apply real migrations once per run so the schema matches production
  • Respawn deletes data in foreign-key order and skips __EFMigrationsHistory; cost grows with row count, so keep per-test data small
  • Transaction rollback is fastest but fails when the code under test commits or uses its own connection
  • Parallel tests sharing one database cause random failures: serialise them in one collection or give each collection its own database

⏱ 30-second answer

The EF Core in-memory provider is fast but not a relational database: it ignores constraints, transactions and SQL translation, so tests pass that would fail in production. Microsoft now advises against it for testing.

SQLite in-memory is relational and quick, but it is a different dialect: column types, schemas, collation and some LINQ translations differ from SQL Server.

For real confidence I run SQL Server in a container with Testcontainers, apply the real migrations once, and reset data between tests with Respawn (delete in foreign-key order) or a rolled-back transaction.

The trade-off: a few seconds of container start-up per run in exchange for testing the same engine you ship on.

🗣 Full answer (senior)

How I would answer this in an interview

"There are three options and they trade speed for fidelity. The EF Core in-memory provider is really a dictionary behind DbSet. It doesn't translate LINQ to SQL, so a query that EF can't translate passes in tests and throws in production; it doesn't enforce foreign keys, unique indexes or required columns; and transactions are ignored. Even the EF Core docs now say not to use it for testing. SQLite in-memory is a real relational engine, so constraints and SQL translation are exercised, but it is a different dialect: no schemas, different decimal and DateTimeOffset handling, case-sensitive comparisons by default, and anything SQL Server-specific like FromSql with T-SQL, temporal tables or JSON columns won't behave the same.

So for repository and query tests I use the real engine: Testcontainers starts SQL Server once per test run in a collection fixture, I run Database.MigrateAsync() so the schema comes from the same migrations that go to production, and I reset data between tests. For resetting, Respawn is my default: it reads the foreign-key graph and issues deletes in the right order, skipping __EFMigrationsHistory, usually in tens of milliseconds. Transaction rollback is even faster, but it breaks as soon as the code under test commits its own transaction, uses ExecuteUpdate on a different connection, or the test goes through WebApplicationFactory, where each request gets a new DbContext.

The mistake I see is teams using the in-memory provider for 'integration' tests and then being surprised by a translation exception or a unique-key violation in production. I'd still use fakes for unit testing business logic that sits above the repository, but any test whose point is the query runs against SQL Server."


Options compared

Option Fidelity to SQL Server Speed Main gaps
EF Core in-memory provider Low Fastest No SQL translation, constraints, transactions or raw SQL
SQLite in-memory Medium Fast Dialect: schemas, types, collation, T-SQL features
LocalDB High Medium Windows only; not in Linux CI agents
SQL Server via Testcontainers Production-level Container start ~5–15 s, then fast Needs Docker in CI
Azure SQL test database Production-level Network latency Shared state, cost

Resetting state

Strategy Speed Works when Breaks when
Respawn ~10–100 ms Almost always Tables you forgot to ignore (seed/reference data)
Transaction rollback ~1 ms Single connection, code doesn't commit Code commits, multiple contexts, WAF requests
Database per test class Seconds Full isolation for parallel classes Many classes: start-up cost adds up
Snapshot restore Seconds Large seeded datasets Container restarts

Production example

On [a claims system], [about 40] repository tests used the in-memory provider and all passed while a GroupBy query threw a translation exception in production. Moving them to SQL Server in Testcontainers with Respawn added [about 12 seconds] of container start to a [6-minute] pipeline and immediately surfaced [two more] untranslatable queries and a missing unique index.

🔍 What the interviewer is checking

Checks whether the candidate knows the fidelity gaps of fake databases and can set up fast, isolated tests against a real engine.

Green flags

  • Explains why the in-memory provider is misleading (no translation, constraints, transactions)
  • Names concrete SQLite dialect gaps
  • Uses Testcontainers with migrations applied once
  • Knows when transaction rollback fails and uses Respawn

Red flags

  • In-memory provider as the integration-test strategy
  • A new container per test
  • No plan for parallel isolation

📚 Learn in depth

1. What the in-memory provider really is

LINQ query
   │ EF Core in-memory provider
   ▼
LINQ-to-Objects over in-memory lists  (no SQL, no relational rules)

LINQ query
   │ SqlServer provider
   ▼
Expression tree -> SQL -> SQL Server optimiser -> rows

Because the in-memory provider evaluates in .NET, it can run methods that SQL Server can't (string.Format, custom C# methods), and it uses C# semantics: string comparison is case-sensitive, nulls behave like C# nulls, not SQL three-valued logic. Microsoft's guidance for EF Core is to avoid it for testing and prefer the real database or the repository pattern with fakes.

2. SQLite's dialect gaps

Area SQL Server SQLite
Schemas (dbo.) Yes No (EF ignores them)
decimal Exact Stored as TEXT/REAL; ordering and sum limitations in EF
DateTimeOffset Native Limited ordering/comparison in EF
Collation Usually case-insensitive Case-sensitive by default
Sequences, temporal tables, JSON columns Yes No / different

It also needs the connection kept open for an in-memory database to survive between contexts.

3. The container lifecycle

Test run starts
  └─ Collection fixture: MsSqlContainer.StartAsync()   (once, ~5-15 s)
       └─ db.Database.MigrateAsync()                    (once)
       └─ Respawner.CreateAsync(conn, options)          (reads FK graph once)
  └─ Each test: Arrange data -> Act -> Assert -> ResetAsync()
Test run ends
  └─ DisposeAsync() stops the container (Ryuk cleans up if the process dies)

4. How Respawn decides the order

Respawn queries INFORMATION_SCHEMA / sys.foreign_keys to build a dependency graph, then generates DELETE statements from leaf tables to root tables (it can also reseed identities). The generated script is cached on the Respawner, so each reset is one round trip. Tables in TablesToIgnore (migration history, reference data) are left alone.

5. Why transaction rollback breaks

Rollback relies on every command running on the same connection inside one open transaction. It fails when:

  • the code under test calls BeginTransaction and Commit itself (nested transactions aren't real in SQL Server);
  • the request goes through WebApplicationFactory, which creates a new scope and DbContext per request;
  • background services or ExecuteUpdate use another connection.

6. Parallelism

xUnit runs test collections in parallel. Tests that share one database must be in the same collection ([Collection("db")]) so they run serially, or each collection gets its own database name on the same container.

Try it yourself

  1. Write a query with a unique index violation; run it on the in-memory provider and on SQL Server in a container.
  2. Write a LINQ query using a custom C# method in Where; compare providers.
  3. Time Respawner.ResetAsync on a schema with 30 tables.
  4. Try transaction rollback with a test that goes through WebApplicationFactory and see the data leak.
  5. Run two collections in parallel against one database without isolation and observe the flakes.

💻 Code

An xUnit collection fixture that starts SQL Server once, applies migrations, and resets data with Respawn after each test.

#nullable enable
namespace Claims.Tests;

using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Respawn;
using Respawn.Graph;
using Testcontainers.MsSql;
using Xunit;

// Code under test
public sealed class Claim
{
    public int Id { get; set; }
    public required string Reference { get; set; }
    public decimal Amount { get; set; }
}

public sealed class ClaimsDb(DbContextOptions<ClaimsDb> options) : DbContext(options)
{
    public DbSet<Claim> Claims => Set<Claim>();
    protected override void OnModelCreating(ModelBuilder b)
    {
        b.Entity<Claim>().HasIndex(c => c.Reference).IsUnique();
        b.Entity<Claim>().Property(c => c.Amount).HasPrecision(18, 2);
    }
}

// One SQL Server container for every test in the "db" collection
public sealed class SqlServerFixture : IAsyncLifetime
{
    private readonly MsSqlContainer _sql = new MsSqlBuilder()
        .WithImage("mcr.microsoft.com/mssql/server:2022-latest")
        .Build();
    private Respawner _respawner = null!;

    public string ConnectionString => _sql.GetConnectionString();

    public ClaimsDb CreateDb() => new(new DbContextOptionsBuilder<ClaimsDb>()
        .UseSqlServer(ConnectionString).Options);

    public async ValueTask InitializeAsync()
    {
        await _sql.StartAsync();
        await using var db = CreateDb();
        await db.Database.EnsureCreatedAsync(); // in a real project: MigrateAsync() with your migrations

        await using var conn = new SqlConnection(ConnectionString);
        await conn.OpenAsync();
        _respawner = await Respawner.CreateAsync(conn, new RespawnerOptions
        {
            DbAdapter = DbAdapter.SqlServer,
            TablesToIgnore = [new Table("__EFMigrationsHistory")]
        });
    }

    public async Task ResetAsync()
    {
        await using var conn = new SqlConnection(ConnectionString);
        await conn.OpenAsync();
        await _respawner.ResetAsync(conn);
    }

    public async ValueTask DisposeAsync() => await _sql.DisposeAsync();
}

[CollectionDefinition("db")]
public sealed class DbCollection : ICollectionFixture<SqlServerFixture>;

[Collection("db")] // tests sharing the database run serially
public sealed class ClaimRepositoryTests(SqlServerFixture fx) : IAsyncLifetime
{
    [Fact]
    public async Task DuplicateReference_IsRejectedByUniqueIndex()
    {
        var ct = TestContext.Current.CancellationToken;
        await using var db = fx.CreateDb();
        db.Claims.Add(new Claim { Reference = "CL-1", Amount = 100m });
        await db.SaveChangesAsync(ct);

        db.Claims.Add(new Claim { Reference = "CL-1", Amount = 50m });

        // The in-memory provider would let this pass; SQL Server enforces the index
        await Assert.ThrowsAsync<DbUpdateException>(() => db.SaveChangesAsync(ct));
    }

    public ValueTask InitializeAsync() => ValueTask.CompletedTask;
    public async ValueTask DisposeAsync() => await fx.ResetAsync();
}

⚠ Common mistakes

  • Mistake: Using the EF Core in-memory provider for integration tests. Why it is wrong: No SQL translation, constraints or transactions, so tests pass on queries that fail in production. Instead: SQL Server in a container, or SQLite only where dialect gaps don't matter.
  • Mistake: Treating SQLite as equivalent to SQL Server. Why it is wrong: Decimals, DateTimeOffset, collation, schemas and T-SQL features differ. Instead: Use SQLite for speed only on simple schemas; run the query tests on SQL Server.
  • Mistake: Building the schema with EnsureCreated in tests while production uses migrations. Why it is wrong: Migrations go untested and can drift from the model. Instead: MigrateAsync() once per run.
  • Mistake: Relying on transaction rollback for tests that go through HTTP. Why it is wrong: Each request uses its own DbContext and connection, so data leaks between tests. Instead: Respawn or a database per test class.
  • Mistake: Forgetting to exclude reference or seed tables from Respawn. Why it is wrong: Lookup data is wiped and later tests fail. Instead: Add them to TablesToIgnore or reseed after reset.
  • Mistake: Running database test classes in parallel against one database. Why it is wrong: xUnit runs collections in parallel by default, so one test's Respawn reset or inserted rows land in the middle of another test. The failures are intermittent, depend on timing and CI agent speed, and look like product bugs, which wastes hours and erodes trust in the suite. Instead: Put every class that shares a database in one [Collection] so they run serially, or give each collection its own database on the shared container.
  • Mistake: Seeding thousands of rows per test. Why it is wrong: Respawn deletes are proportional to data volume, so resets climb from milliseconds to seconds. Instead: Insert only the rows each test needs; load large reference data once and add it to TablesToIgnore.
  • Mistake: Starting a new container per test. Why it is wrong: Adds 5–15 seconds per test. Instead: Collection or assembly fixture; reset data, not the container.

🏛 Senior insight: trade-offs

The rule I give teams: fake the database to test logic, use the real database to test data access. Once you accept that, the choice is mostly about how to make the real database cheap, and in .NET 10 Testcontainers plus Respawn is the standard answer. The remaining decision is isolation versus speed.

In practice I balance it by test purpose. The inner loop while coding should give feedback in seconds, so domain logic runs against fakes and is never blocked by Docker. Data-access and endpoint tests run against SQL Server on every PR, because that is where fidelity pays. If that layer grows past a few minutes, I don't drop fidelity; I split it: shared container per run, a database per collection so collections can run in parallel, and small per-test datasets so resets stay in the tens of milliseconds. Only when a team has no container runtime at all would I accept SQLite, and then I'd add a nightly run against real SQL Server.

Option When it fits Cost When not to
Repository fake Unit tests of business rules above data access Fake must stay simple Testing the query itself
SQLite in-memory Simple schemas, fast inner loop Dialect surprises SQL Server features, decimals, JSON columns
SQL Server container + Respawn Default for data-access and API tests Docker in CI, ~10 s start No container runtime available
Database per collection Parallel collections, heavy suites More start-up and memory Small suites
Reset strategy Typical cost Scales with
Transaction rollback ~1 ms Nothing (but limited applicability)
Respawn ~10–100 ms Rows to delete and tables in the graph
Recreate database Seconds Schema size and migrations

I measure the setup by suite duration and flaky-test rate, and I check the escaped-defect log: if data bugs still reach production, the tests aren't using the real engine or real migrations.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate is asked to justify not using the in-memory provider Why: Checks the specific behaviours the in-memory provider gets wrong
    How to answer

    Not for anything that tests data access. The EF Core in-memory provider runs LINQ against in-memory collections; it never generates SQL, so untranslatable queries, SQL Server collation and case-sensitivity, null semantics, constraints, foreign keys, unique indexes and transactions all behave differently, and tests pass that would fail on SQL Server. Microsoft's EF Core testing docs discourage it for testing. It can still serve quick tests of application logic that merely uses a DbContext, where speed matters more than fidelity. For integration tests use SQL Server in Testcontainers (or SQLite in-memory as a compromise with a different dialect), and reset state with Respawn or rolled-back transactions.

  2. When: Candidate mentions Testcontainers Why: Checks fixture setup, reuse and CI requirements for containers
    How to answer

    Testcontainers for .NET starts real Docker containers from test code and gives you their connection details. With Testcontainers.MsSql you build new MsSqlBuilder().WithImage("mcr.microsoft.com/mssql/server:2022-latest").Build(), await StartAsync() in an IAsyncLifetime fixture, and pass GetConnectionString() to EF Core. Testcontainers.Redis works the same way.

    To keep it fast:

    • Share one container per class or collection, and apply migrations once.
    • Reset data between tests with Respawn instead of new containers.
    • Use WithReuse(true) locally to skip start-up between runs.

    In CI you need a Docker host: Linux GitHub Actions runners and Microsoft-hosted Ubuntu agents have one. The trade-off is seconds of start-up and a Docker dependency for tests that behave like production, unlike the in-memory provider.

  3. When: Candidate tests through HTTP with a real database Why: Checks wiring WebApplicationFactory to a per-class container database
    How to answer

    Derive a factory from WebApplicationFactory<Program> and implement IAsyncLifetime. InitializeAsync starts an MsSqlContainer, and DisposeAsync disposes the container and then the factory. In ConfigureWebHost, point the app at the container with UseSetting("ConnectionStrings:Orders", ...). You can also swap the DbContext registration in ConfigureTestServices.

    Run EF Core migrations once per fixture, so the tests use the real schema. Then reset rows before each test with Respawn, which deletes data in foreign-key order and keeps the schema.

    Use it as an IClassFixture and every class gets its own database. For speed, share one container and give each class a unique database name. The trade-off is that real SQL Server catches what in-memory providers hide (constraints, transactions, SQL translation), at the price of Docker and a few seconds of start-up.

🛠 Real-world problems: how you handle them

Green tests, production translation exception on a report query
Situation
A .NET 10 claims API on Azure SQL in Australia East, [about 300k claims]. Repository tests used the EF Core in-memory provider. A new monthly summary endpoint grouped claims by status and month.
Signals
Application Insights showed `InvalidOperationException: The LINQ expression ... could not be translated` on the new endpoint immediately after release; 100% failure rate on that route; all CI tests green.
Investigation
Reproduced locally against SQL Server; the GroupBy used a custom C# helper to format the month, which the in-memory provider evaluated in .NET but the SQL Server provider couldn't translate. Audited the other repository tests and found they all ran on the in-memory provider, including ones relying on unique indexes.
Resolution
Immediate: rewrote the projection to group by `Year` and `Month` columns and format in memory after the query; hotfix released. Real fix: moved all repository tests to SQL Server via Testcontainers in a collection fixture, applying migrations once and resetting with Respawn.
Prevention
Team guideline (ADR) banning the in-memory provider for data-access tests; repository and endpoint tests run on SQL Server in CI; a test that applies all migrations to an empty database on every PR; EF Core warnings for client evaluation turned into errors.

How to tell it (STAR)

**S:** At [company] a new reporting endpoint failed on every call in production even though every test was green. **T:** I needed to fix it fast and work out why our tests missed it. **A:** I traced it to a GroupBy that SQL Server couldn't translate; our tests used the EF Core in-memory provider, which just ran it in .NET. After the hotfix, I moved our [40] repository tests to SQL Server in Testcontainers with migrations applied once and Respawn between tests, and wrote an ADR so new tests followed suit. **R:** The pipeline grew by [about 12 seconds], the move immediately caught [two] more untranslatable queries and a missing unique index, and we had [no] data-access regressions in the following [two quarters].

↩ Usually asked after

More in Testing Practices

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me