الانتقال إلى المحتوى
.NETTesting في .NET· 7 دقائق للقراءة

Why Tests Pass on the EF Core InMemory Provider and Fail in Production

The InMemory provider runs your LINQ as C# over lists. It skips constraints, compares strings its own way and accepts queries SQL Server rejects.

ReadIn

مقال كل يوم يفرق معاك

22 نوفمبر 2026
  • كاتب موثّق
  • EF Core 10
محتويات المقال

A sign-up endpoint must reject an email that's already registered, whatever its case. The team's tests use UseInMemoryDatabase, and the first version of the check failed the test "rejects ana@example.com when Ana@Example.com exists". So the developer rewrote the query with string.Equals(c.Email, email, StringComparison.OrdinalIgnoreCase). The test turned green and the change shipped. In production, on SQL Server, every sign-up now fails with InvalidOperationException: The LINQ expression ... could not be translated. The fake didn't just miss a bug. It caused one.

The common misconception

The belief: the InMemory provider is a fast, faithful stand-in for the real database. Same DbContext, same LINQ, no server to install, no data to clean up, and tests that run in milliseconds.

It's easy to see why teams reach for it. It ships with EF Core and takes one line to configure. Plenty of tutorials and sample test projects use it. For simple add-and-find tests it really does behave like a database, so the first few hundred tests go green and build trust. And a real database in tests sounds slow and fiddly to set up, so a fake that "just works" feels like the pragmatic choice.

What actually happens

It's a list with a DbContext in front

The InMemory provider isn't relational. Microsoft's docs say it was originally designed to support EF Core's own internal testing, that new features aren't being added to it, and that using it as a database fake is "highly discouraged". Your LINQ never becomes SQL: it runs as .NET code over the stored objects. That single fact explains every difference below. In tests with EF Core 10, the same operations ran against InMemory, SQLite in-memory and SQL Server LocalDB.

Constraints the database enforces don't exist

A real database rejects bad data. InMemory stores it.

  • Foreign keys: an order pointing at customer 999, who doesn't exist, saved on InMemory. SQLite and SQL Server both refused it.
  • Unique indexes: a second customer with the same email saved on InMemory. Both databases threw.
  • Column lengths: a 50-character name in a HasMaxLength(20) column saved on InMemory and SQLite. SQL Server threw "String or binary data would be truncated".
  • Decimal precision: a price of 10.555 in a decimal(18,2) column read back as 10.555 on InMemory and SQLite, and as 10.56 on SQL Server.

Each of these is a DbUpdateException or a rounding difference your tests will never see.

Queries are judged by C#, not SQL

Because the query runs as C#, string equality is ordinal and case-sensitive. SQL Server's default is case-insensitive, so c.Email == "ana@example.com" found Ana@Example.com on SQL Server and found nothing on InMemory. Worse, InMemory accepts expressions a relational provider can't translate. string.Equals with StringComparison.OrdinalIgnoreCase ran fine on InMemory and threw "could not be translated" on both SQLite and SQL Server.

Whole features are missing

Starting a transaction on InMemory threw an error for TransactionIgnoredWarning: transactions aren't supported, and if you suppress the warning they're silently ignored, so a rollback test proves nothing. FromSql threw, and so did ExecuteUpdate, which only relational providers support. Deleting an order without loading its lines left the lines behind as orphans, because InMemory doesn't support cascade deletes in the database. SQL Server and SQLite deleted them.

It isn't even the fast option

Speed is the usual reason to pick it, and Microsoft's docs say the provider hasn't been optimized for performance and is generally slower than SQLite in-memory, or even than your production database. EF Core itself runs over 30,000 tests against SQL Server, which complete in a few minutes on every commit.

The fix: test the query where it will run

C# SignUp.cs
using Microsoft.EntityFrameworkCore;public sealed class SignUp(ShopDb db){    // Rewritten until the InMemory test passed    public Task<bool> EmailTakenAsync(string email, CancellationToken ct) =>        db.Customers.AnyAsync(c => string.Equals(            c.Email, email, StringComparison.OrdinalIgnoreCase), ct);    // SQL Server: InvalidOperationException, could not be translated}

The right version doesn't depend on any collation, and the unique index makes the database itself reject a duplicate that slips past the check. Then test it against SQL Server, isolating each test in a transaction that's never committed, as Microsoft's testing guide recommends:

C# SignUpTests.cs
using Microsoft.EntityFrameworkCore;using Shop;using Xunit;public sealed class SignUpTests(SqlServerFixture fixture)    : IClassFixture<SqlServerFixture>{    [Fact]    public async Task Finds_an_email_in_any_case()    {        // Real SQL Server: a container in CI, LocalDB on a dev machine        await using var db = fixture.CreateContext();        // Never committed, so it's rolled back when the context is disposed        await db.Database.BeginTransactionAsync();        db.Customers.Add(new Customer            { Email = "Ana@Example.com", NormalizedEmail = "ANA@EXAMPLE.COM" });        await db.SaveChangesAsync();        db.ChangeTracker.Clear();        var taken = await new SignUp(db)            .EmailTakenAsync("ana@example.com", default);        Assert.True(taken);    }}

The fixture creates the database once per test run with EnsureDeleted and EnsureCreated. In a test on LocalDB, the check returned true, and the table was empty again once the context was disposed.

BehaviorInMemorySQLite in-memorySQL Server
Foreign keys and unique indexesNot enforcedEnforcedEnforced
HasMaxLength and decimal(18,2)IgnoredIgnoredEnforced, rounded
== on strings that differ in caseNo matchNo matchMatch
Untranslatable LINQRunsThrowsThrows
Transactions, raw SQL, ExecuteUpdateNot supportedSupportedSupported

How to apply it in your project

  1. Find the fakesSearch your test projects for UseInMemoryDatabase and list which tests check queries, constraints or transactions. Those are the ones giving false confidence.
  2. Stand up the real engineRun the production database in a container, with Testcontainers or your CI's services, or use SQL Server Developer Edition or LocalDB on developer machines.
  3. Isolate with transactionsCreate the database once per run, wrap each writing test in a transaction you never commit, and call ChangeTracker.Clear() before reading back what you wrote.
  4. Move logic tests above the queriesWhere you want speed, test business logic against a stubbed interface that returns results, and keep the LINQ in classes that are tested only against the database.

Key takeaways

  • The InMemory provider runs LINQ as C# over collections; it was built for EF Core's own tests and Microsoft discourages it as a fake.
  • It doesn't enforce foreign keys, unique indexes, lengths or precision, and it compares strings with C# rules.
  • It runs queries that SQL Server can't translate, so a test can pass for code that always fails in production.
  • Transactions, raw SQL, ExecuteUpdate and database cascades don't work on it at all.
  • Test queries against the engine you ship on, isolated with transactions, and stub above the data access for fast logic tests.

📚 المصادر

  1. Choosing a testing strategy — EF Core, Microsoft Learn
  2. In-memory Database Provider — EF Core, Microsoft Learn
  3. Testing against your Production Database System — EF Core, Microsoft Learn
  4. Testing EF Core Applications — Microsoft Learn
  5. Cascade Delete — EF Core, Microsoft Learn

التعليقات (0)