Lesson 79 of 93 · 5 min read · Updated

Choosing an EF Core Test Database Honestly: InMemory vs SQLite vs the Real Thing

Every EF Core project has to decide what database its tests run against. The EF InMemory provider is the easiest choice, and it is also the one that hides the most bugs. This lesson compares three options with tests that prove the differences: one where InMemory gives a misleading green result, one where SQLite catches the same bug, and one where SQLite also lets a constraint slip through. The goal is to pick a provider by what it can catch, not by how easy it is to set up.

Technical Requirements

  1. .NET 11 SDK
  2. xUnit 2.9.3
  3. Microsoft.EntityFrameworkCore.InMemory 11.0.0
  4. Microsoft.EntityFrameworkCore.Sqlite 11.0.0
  5. FluentAssertions 7.2.2
  6. Docker is not required for this lesson. A production database in a container (Testcontainers) is the third option and is mentioned for comparison.

The Model and Its Constraints

The AppDbContext for a Books API defines a unique index on ISBN and maximum lengths for the text columns. These rules live in the database schema, not in C# code.

M09.IntegrationApi/Data/AppDbContext.cs

modelBuilder.Entity<Book>(entity =>
{
entity.HasKey(x => x.Id);

// Relational constraint: the same ISBN cannot be added twice.
entity.HasIndex(x => x.Isbn).IsUnique();

entity.Property(x => x.Isbn).IsRequired().HasMaxLength(20);
entity.Property(x => x.Title).IsRequired().HasMaxLength(200);
entity.Property(x => x.Author).IsRequired().HasMaxLength(100);

The test class builds two kinds of context from the same model. The InMemory context gets a unique database name per test. The SQLite context opens a connection and keeps it open, because an in-memory SQLite database is deleted when its connection closes.

M09.IntegrationApi.Tests/EfCoreProviderTests.cs

private static AppDbContext CreateInMemoryContext()
{
var options = new DbContextOptionsBuilder<AppDbContext>()
.UseInMemoryDatabase($"test-{Guid.NewGuid()}")
.Options;

return new AppDbContext(options);
}

private static (AppDbContext Db, SqliteConnection Connection) CreateSqliteContext()
{
// We MUST keep the connection open: if it closes, the in-memory database is deleted.
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();

var options = new DbContextOptionsBuilder<AppDbContext>()
.UseSqlite(connection)
.Options;

var db = new AppDbContext(options);
db.Database.EnsureCreated();

return (db, connection);
}

InMemory Ignores the Unique Index

Here is the first test. It adds two books with the same ISBN and saves. On a real relational database this must fail.

M09.IntegrationApi.Tests/EfCoreProviderTests.cs

[Fact]
public async Task InMemoryProvider_SilentlyIgnoresUniqueIndex()
{
// DANGER: the InMemory provider does NOT enforce the unique index.
// Code that passes this test gets a conflict error in production.
await using var db = CreateInMemoryContext();

db.Books.Add(NewBook("978-AYNI"));
db.Books.Add(NewBook("978-AYNI"));

var act = async () => await db.SaveChangesAsync();

await act.Should().NotThrowAsync(
"EF InMemory does not enforce relational constraints — that is why it is misleading");

db.Books.Should().HaveCount(2);
}

The test is written to pass, and that is the point. It documents that InMemory accepted two rows that production would reject. If your duplicate-handling code were tested only against InMemory, every test would be green and the first real duplicate would fail with a database exception. The InMemory provider is not a relational database. It does not enforce unique indexes, foreign keys or transactions, and it runs LINQ in memory instead of translating it to SQL. Microsoft's own testing guidance advises against using it to test database behaviour.

SQLite Enforces the Same Index

The same scenario against SQLite in-memory behaves like a real database:

M09.IntegrationApi.Tests/EfCoreProviderTests.cs

[Fact]
public async Task SqliteProvider_EnforcesUniqueIndex()
{
// SQLite is relational: the same constraint is REALLY enforced.
var (db, connection) = CreateSqliteContext();
await using var _ = db;
await using var __ = connection;

db.Books.Add(NewBook("978-AYNI"));
db.Books.Add(NewBook("978-AYNI"));

var act = async () => await db.SaveChangesAsync();

await act.Should().ThrowAsync<DbUpdateException>();
}

EnsureCreated built a real schema with a real UNIQUE index, so the second insert fails and EF Core wraps the error in a DbUpdateException. This is the behaviour your API's 409 handling must be ready for.

Pitfall: SQLite Has Limits Too

SQLite is closer to production than InMemory, but it is not your production database. The next test shows a constraint it does not enforce:

M09.IntegrationApi.Tests/EfCoreProviderTests.cs

[Fact]
public async Task SqliteProvider_EnforcesMaxLength()
{
// Another constraint that comes from the relational schema.
var (db, connection) = CreateSqliteContext();
await using var _ = db;
await using var __ = connection;

// SQLite does not enforce length limits by default; knowing this is part of
// the lesson "know your provider's differences".
// That is why truly critical constraints should be tested against the production database.
db.Books.Add(NewBook("978-COK-COK-UZUN-BIR-ISBN-DEGERI"));

var act = async () => await db.SaveChangesAsync();

await act.Should().NotThrowAsync();
}

The ISBN column is declared with HasMaxLength(20), and the value is longer. SQLite stores it anyway, because SQLite treats VARCHAR(20) as plain TEXT and ignores the length. SQL Server or PostgreSQL would reject the row. The test name says "enforces", but the assertion proves the opposite, on purpose: it pins down a known gap so nobody relies on SQLite for this rule.

Other common SQLite differences: its type system is dynamic, LIKE is case-insensitive for ASCII by default, date functions differ, and some types such as decimal and DateTimeOffset need value converters.

Picking the Right Option

TestResult
InMemoryProvider_SilentlyIgnoresUniqueIndexThe unique index is not applied: a misleading green test
SqliteProvider_EnforcesUniqueIndexThrows DbUpdateException: real behaviour
SqliteProvider_SupportsTransactionsAndRollbackTransactions really work
SqliteProvider_EnforcesMaxLengthNot enforced: SQLite has limits too

The transaction test is covered in the next lesson, together with query translation. Put the results side by side and the choice becomes a trade-off between speed and fidelity:

OptionSpeedFidelityWhen to use
EF InMemoryFastestNot relationalDo not use it to test database behaviour
SQLite in-memoryFastRelational, with provider differencesFast integration tests
Production database (Testcontainers)SlowestHighestWhen query and migration fidelity is critical

A reasonable default is SQLite in-memory for most integration tests, plus a smaller set of tests against the production engine in a container for the rules where SQLite is known to differ.

Summary

  1. The EF InMemory provider is not relational: it ignores unique indexes, foreign keys and transactions.
  2. A test that passes on InMemory can hide a bug that fails on the first real duplicate.
  3. SQLite in-memory enforces relational constraints such as unique indexes and supports transactions.
  4. SQLite ignores HasMaxLength and has other provider differences; know them and test critical rules on the production engine.
  5. Choose the test database by what it can catch, not by how easy it is to set up.