.NET Development

AI-written LINQ and EF Core: deterministic tests on the SQL they generate

Team Nippysoft
• • 22 min read
AI-written LINQ and EF Core: deterministic tests on the SQL they generate

A change adds the line count and the total of each order to the orders list. It comes with its own test, which checks the values and passes. It also issues 11 SQL commands for every page of 10 orders: one for the page and one more per order. We wrote it by hand, the way an AI agent might, and three tests stopped it. They don't read the code: they check the SQL that EF Core is about to execute and what the read leaves tracked.

The code is in ef-core-query-guardrails: .NET 10, EF Core 10.0.14 and in-memory SQLite, with two use cases, three guards per case and a few fixed rules. Every output in this post is verbatim, from dotnet test, from the hostile input bench or from a separate probe.

Reading isn't deterministic; checking the SQL is

A review, whether a person or a model does it, depends on the reader spotting the problem. With a model, the answer can also change from one run to the next. Anthropic's glossary warns about it: "Even with temperature set to 0, the results will not be fully deterministic, and identical inputs might produce different outputs across API calls."

The Claude Code best practices split instructions into two kinds. A skill belongs to the first: "Non-deterministic: you write the instruction, and Claude (the model) reads it. This can be your prompt, CLAUDE.md, or a skill." The second kind: "Deterministic: you configure the instruction, and Claude Code (the harness) has to execute this." For deciding whether work is done, that guide puts "Tests, typecheck, a Stop hook, CI" on the deterministic side.

That gives this repo its split: the skill asks for the tests to run, and CI or a Stop hook enforces it. The tests have no opinion on whether a query looks good. Each read use case has three of them:

TestWhat it checksFails when
*_sql_matches_snapshotThe text of every command EF Core was about to execute for the use caseIt differs from the approved file in Snapshots/
*_stays_within_query_budgetHow many commands it issuedIt issues a number of commands other than its budget, 1 for both cases in the repo
*_tracks_nothingChangeTracker.Entries() after the readThe read leaves entities tracked

Seeing everything EF Core is about to execute

ToQueryString returns the SQL for a LINQ query, and its reference calls it "The query string for debugging." It's good for looking at one query. It doesn't see the ones that come out of a loop, which is where an N+1 starts, and it doesn't count how many a use case issues. The EF Core projections post already uses it to measure when a Select tracks; this post doesn't repeat that.

Seeing everything takes a command interceptor: "DbCommandInterceptor.ReaderExecuting is called before a query is executed". QueryCounter records the text of every command EF Core is about to execute, whether reader, scalar or non-query, sync or async. It keeps only CommandText, not the parameters:

using System.Data.Common;
using Microsoft.EntityFrameworkCore.Diagnostics;

namespace Shop.Tests.Guardrails;

/// <summary>
/// Records the text of every command EF Core is about to execute: readers, scalars and non-queries,
/// sync and async. The *Executing methods run before the command does. Only CommandText is kept,
/// not the parameters. Commands run through a connection outside EF Core are not seen.
/// </summary>
public sealed class QueryCounter : DbCommandInterceptor
{
    private readonly List<string> _commands = [];

    public IReadOnlyList<string> Commands => _commands;

    public int Count => _commands.Count;

    public override InterceptionResult<DbDataReader> ReaderExecuting(
        DbCommand command, CommandEventData eventData, InterceptionResult<DbDataReader> result)
    {
        _commands.Add(command.CommandText);
        return result;
    }

    public override ValueTask<InterceptionResult<DbDataReader>> ReaderExecutingAsync(
        DbCommand command, CommandEventData eventData, InterceptionResult<DbDataReader> result,
        CancellationToken cancellationToken = default)
    {
        _commands.Add(command.CommandText);
        return ValueTask.FromResult(result);
    }

    public override InterceptionResult<object> ScalarExecuting(
        DbCommand command, CommandEventData eventData, InterceptionResult<object> result)
    {
        _commands.Add(command.CommandText);
        return result;
    }

    public override ValueTask<InterceptionResult<object>> ScalarExecutingAsync(
        DbCommand command, CommandEventData eventData, InterceptionResult<object> result,
        CancellationToken cancellationToken = default)
    {
        _commands.Add(command.CommandText);
        return ValueTask.FromResult(result);
    }

    public override InterceptionResult<int> NonQueryExecuting(
        DbCommand command, CommandEventData eventData, InterceptionResult<int> result)
    {
        _commands.Add(command.CommandText);
        return result;
    }

    public override ValueTask<InterceptionResult<int>> NonQueryExecutingAsync(
        DbCommand command, CommandEventData eventData, InterceptionResult<int> result,
        CancellationToken cancellationToken = default)
    {
        _commands.Add(command.CommandText);
        return ValueTask.FromResult(result);
    }
}

On the bench it counted 1 command for a synchronous ToList, 1 for FromSqlRaw and 1 for ExecuteUpdate. Each context gets its own counter: interceptors "are registered per DbContext instance when the context is configured", and each test creates its own when it asks for a context:

/// <summary>A context with the app rules and, when given, a counter of every command.</summary>
public ShopContext CreateContext(QueryCounter? counter = null)
{
    var builder = ShopContext.ApplyRules(new DbContextOptionsBuilder<ShopContext>().UseSqlite(_connection));
    if (counter is not null)
    {
        builder.AddInterceptors(counter);
    }

    return new ShopContext(builder.Options);
}

What it misses is a DbCommand created by hand on the same connection. On the bench, that command counted all 120 orders and the counter stayed at 0. If a use case mixes ADO.NET with EF Core, its budget doesn't count that part.

The approved SQL is kept in a file

Each use case has its approved SQL in tests/Shop.Tests/Snapshots/. These are the three tests for the recent orders list, with the full-page check they run before anything else:

private const int ListRecentBudget = 1;
private const int GetWithLinesBudget = 1;
private const int PageSize = 10;

[Fact]
public async Task ListRecent_sql_matches_snapshot()
{
    var counter = new QueryCounter();
    await using var db = database.CreateContext(counter);

    // Page 3: offset 20 and size 10 differ. With equal values, EF Core 10.0.14 on SQLite sent one parameter for both.
    var page = await OrderQueries.ListRecentAsync(db, new PageRequest(3, PageSize));

    AssertFullPage(page);
    SnapshotAssert.Matches("ListRecent", counter.Commands);
}

[Fact]
public async Task ListRecent_stays_within_query_budget()
{
    var counter = new QueryCounter();
    await using var db = database.CreateContext(counter);

    var page = await OrderQueries.ListRecentAsync(db, new PageRequest(1, PageSize));

    AssertFullPage(page);
    Assert.Equal(ListRecentBudget, counter.Count);
}

[Fact]
public async Task ListRecent_tracks_nothing()
{
    await using var db = database.CreateContext();

    var page = await OrderQueries.ListRecentAsync(db, new PageRequest(1, PageSize));

    AssertFullPage(page);
    Assert.Empty(db.ChangeTracker.Entries());
}

private static void AssertFullPage(List<OrderSummary> page) =>
    Assert.True(page.Count == PageSize, $"Expected a full page of {PageSize} rows, got {page.Count}. Seed enough data for the page the test asks for.");

And this is the approved SQL for ListRecent, a single command:

SELECT "o0"."Id", "c"."Name", "o0"."PlacedAt", (
    SELECT COUNT(*)
    FROM "OrderLines" AS "o1"
    WHERE "o0"."Id" = "o1"."OrderId"), (
    SELECT COALESCE(SUM(CAST("o2"."Quantity" AS INTEGER) * "o2"."UnitPriceCents"), 0)
    FROM "OrderLines" AS "o2"
    WHERE "o0"."Id" = "o2"."OrderId")
FROM (
    SELECT "o"."Id", "o"."CustomerId", "o"."PlacedAt"
    FROM "Orders" AS "o"
    ORDER BY "o"."PlacedAt" DESC, "o"."Id" DESC
    LIMIT @p1 OFFSET @p
) AS "o0"
INNER JOIN "Customers" AS "c" ON "o0"."CustomerId" = "c"."Id"
ORDER BY "o0"."PlacedAt" DESC, "o0"."Id" DESC

The snapshot compares the text of the SQL, not its parameters: since the counter keeps only CommandText, parameter values, types and sizes aren't compared. It verifies the shape of the query; result tests, like OrderTotalsTests, and specific checks cover the rest.

When the text changes, the test writes ListRecent.received.sql next to the approved file and fails with the number of commands on each side and the first line that differs. The approved file is never touched. A person compares both files and, if the new SQL is right, renames the .received.sql and commits it; *.received.sql is in .gitignore.

namespace Shop.Tests.Guardrails;

/// <summary>
/// Compares the SQL a use case was about to execute with an approved file. The file holds command text only,
/// without parameter values. The text can still depend on the values (with EF Core 10.0.14 and
/// SQLite, Skip and Take with equal values shared one parameter), so each test uses fixed inputs.
/// </summary>
public static class SqlSnapshot
{
    private const string Separator = "\n-- next command\n";

    public static string Normalize(IEnumerable<string> commands) =>
        string.Join(Separator, commands.Select(NormalizeOne)) + "\n";

    /// <summary>
    /// Returns null when the SQL matches. Otherwise writes name.received.sql next to the
    /// approved file and returns the reason. It never overwrites the approved file.
    /// Creates the directory when it does not exist yet.
    /// </summary>
    public static string? Compare(string directory, string name, IEnumerable<string> commands)
    {
        Directory.CreateDirectory(directory);
        var actual = Normalize(commands);
        var approvedPath = Path.Combine(directory, name + ".sql");
        var receivedPath = Path.Combine(directory, name + ".received.sql");

        if (!File.Exists(approvedPath))
        {
            File.WriteAllText(receivedPath, actual);
            return $"No approved snapshot {name}.sql. Review {name}.received.sql and rename it if it is right.";
        }

        var approved = NormalizeOne(File.ReadAllText(approvedPath)) + "\n";
        if (approved == actual)
        {
            File.Delete(receivedPath);
            return null;
        }

        File.WriteAllText(receivedPath, actual);
        return $"SQL for {name} changed. Approved {CountCommands(approved)} command(s), received {CountCommands(actual)}. "
            + $"{FirstDifference(approved, actual)} Review {name}.received.sql against {name}.sql.";
    }

    private static int CountCommands(string snapshot) =>
        string.IsNullOrWhiteSpace(snapshot) ? 0 : snapshot.Split(Separator).Length;

    private static string NormalizeOne(string sql) =>
        string.Join("\n", sql.Replace("\r\n", "\n").Split('\n').Select(line => line.TrimEnd())).Trim();

    private static string FirstDifference(string expected, string actual)
    {
        var expectedLines = expected.Split('\n');
        var actualLines = actual.Split('\n');
        for (var i = 0; i < Math.Max(expectedLines.Length, actualLines.Length); i++)
        {
            var e = i < expectedLines.Length ? expectedLines[i] : "<end>";
            var a = i < actualLines.Length ? actualLines[i] : "<end>";
            if (e != a)
            {
                return $"First difference at line {i + 1}: approved \"{e}\", received \"{a}\".";
            }
        }

        return "No line differs.";
    }
}

The comparison ignores CRLF line endings, trailing spaces on each line and blank lines at either end: on the bench, an approved file with CRLF and another with extra spaces and lines both matched. If the approved file is missing, the test fails and leaves the .received.sql for review.

using System.Runtime.CompilerServices;
using Xunit;

namespace Shop.Tests.Guardrails;

public static class SnapshotAssert
{
    /// <summary>
    /// Fails when the SQL differs from Snapshots/name.sql, which sits next to the calling test file.
    /// The path comes from the compiler, so it needs the source tree that was built.
    /// </summary>
    public static void Matches(string name, IEnumerable<string> commands, [CallerFilePath] string callerFile = "")
    {
        var directory = Path.Combine(Path.GetDirectoryName(callerFile)!, "Snapshots");
        var reason = SqlSnapshot.Compare(directory, name, commands);
        if (reason is not null)
        {
            Assert.Fail(reason);
        }
    }
}

SnapshotAssert gets the folder path through [CallerFilePath], so it needs the source tree that was built. A build with ContinuousIntegrationBuild=true, common in CI, maps source paths to /_/ and would break it. That's why the test project sets <DeterministicSourcePaths>false</DeterministicSourcePaths>, and with it the whole suite also passed with -p:ContinuousIntegrationBuild=true.

Keep each snapshot's inputs fixed. With EF Core 10.0.14 and SQLite, the SQL text depends on the values passed to Skip and Take. This is the output of a separate probe with the same packages:

skip=4 take=4: LIMIT @p OFFSET @p
skip=4 take=5: LIMIT @p1 OFFSET @p
skip=0 take=4: LIMIT @p1 OFFSET @p
a=3 b=9: WHERE "o"."Id" > @a AND "o"."CustomerId" < @b
a=5 b=5: WHERE "o"."Id" > @a AND "o"."CustomerId" < @b

With equal values, Skip and Take share one parameter; Where doesn't: with a=5 b=5 it still uses @a and @b. The results are correct either way. The snapshot is what breaks: the same query with page 2 of size 10, where the offset equals the size, failed against the approved file with nothing changed. We didn't find this documented, and we only saw it in that version with SQLite. That's why the test uses page 3 of size 10, and its comment says so.

When you upgrade EF Core, review every snapshot. EF Core 10 changed parameter names, and its documentation names this case: "code that depends on the exact parameter names in the generated SQL - such as snapshot tests comparing SQL text, or interceptors and loggers that parse DbCommand.CommandText or inspect DbParameter.ParameterName - needs to be updated to account for the new names."

A command budget per use case

The second guard is a constant: ListRecentBudget = 1. The efficient querying guide describes the pattern it catches: loading a list and then running "another query per blog, loading all its posts; this is sometimes called the N+1 problem, and it can cause very significant performance issues." The guide explains it with lazy loading; the N+1 in this repo is an explicit loop, with the same one query per row.

Measuring time won't catch it on a test database, and the same guide says why: "Crucially, test databases frequently contain little data, so that everything works well while testing, but performance problems suddenly appear when the query starts running on real-world data and many rows are returned." The count doesn't depend on the table's size, but it does depend on the page having rows: an N+1 on an empty page issues one command and tracks nothing. That's why each guard first requires a full page with AssertFullPage. With 120 orders, the page of 10 the test asks for gives 11 commands.

The third guard checks tracking. The EF Core documentation says "No-tracking queries are useful when the results are used in a read-only scenario." The test doesn't look for a call to AsNoTracking: it checks that ChangeTracker.Entries() is empty. A projection to a DTO passes too if it holds only scalar fields; if the DTO embeds entities, those stay tracked. That's what the skill asks for: only scalar fields in the DTO, or AsNoTracking() when returning entities for reading. An entity query without AsNoTracking left 10 tracked entries on the bench.

If the count grows with the page size, it's an N+1. Rewrite the query so the database does the work in one command; don't raise the budget constant.

Rules that throw before any SQL goes out

The guards check the commands EF Core tried to execute. Some mistakes are better stopped earlier, in the query itself, so ShopContext.ApplyRules turns two EF Core warnings into exceptions. You call it wherever the context is configured: on the typed builder, as TestDatabase does, or inside AddDbContext, which passes an untyped builder:

/// <summary>
/// Fixed rules. Call it wherever the context is configured: on the typed builder, as
/// TestDatabase does, or inside AddDbContext, which passes an untyped builder.
/// Each listed warning becomes an exception. Returns the same builder.
/// </summary>
public static TBuilder ApplyRules<TBuilder>(TBuilder builder)
    where TBuilder : DbContextOptionsBuilder
{
    builder.ConfigureWarnings(warnings => warnings.Throw(
        // Skip/Take without OrderBy: pages could repeat or skip rows.
        CoreEventId.RowLimitingOperationWithoutOrderByWarning,
        // First/FirstOrDefault without OrderBy and without a filter: the row is arbitrary.
        CoreEventId.FirstWithoutOrderByAndFilterWarning));
    return builder;
}

On the bench, Skip and Take without OrderBy threw InvalidOperationException with the RowLimitingOperationWithoutOrderByWarning warning, and First with no order and no filter threw with FirstWithoutOrderByAndFilterWarning. That warning doesn't fire when there's a predicate: db.Customers.FirstAsync(c => c.Name.StartsWith("Customer")) passes even if many rows match, and returns whichever one the database gives first. A predicate doesn't guarantee a single row; in review, check that the filter identifies one record, or add an OrderBy. A filter EF Core can't translate already throws with no configuration: its documentation says "So Entity Framework Core blocks such client evaluation and throws a runtime exception."

No rule forces the ordering to be unique. ListRecentAsync orders by date and then by Id, because the pagination guide asks for it: "Regardless of the pagination method used, always make sure that your ordering is fully unique." Whether a new method does the same is up to review. Lists take a PageRequest:

namespace Shop;

/// <summary>
/// The list queries in this repo take a page, so they return at most MaxSize rows.
/// Nothing forces a new list method to take one; that is review.
/// </summary>
public sealed record PageRequest
{
    public const int MaxSize = 100;

    public int Number { get; }
    public int Size { get; }

    public PageRequest(int number, int size)
    {
        ArgumentOutOfRangeException.ThrowIfLessThan(number, 1);
        ArgumentOutOfRangeException.ThrowIfLessThan(size, 1);
        ArgumentOutOfRangeException.ThrowIfGreaterThan(size, MaxSize);

        // Checked so a huge page number fails here instead of wrapping to a negative offset.
        _ = checked((number - 1) * size);

        Number = number;
        Size = size;
    }

    public int Offset => (Number - 1) * Size;
}

Page 0, size 0 and size 101 throw ArgumentOutOfRangeException. Page int.MaxValue with size 100 throws OverflowException instead of passing a negative offset, and page 21474837 returned 0 rows. Nothing stops a new method from returning a list without a PageRequest; that's also left to review. The repo pages with an offset for simplicity. For large tables, the same guide recommends another way: "The recommended alternative to offset-based pagination - sometimes called keyset pagination or seek-based pagination - is to simply use a WHERE clause to skip rows, instead of an offset."

An N+1 that passes its own test

Commit 43544d8, on the agent/order-line-totals branch, adds the line count and the total. It loads the page and then asks for each order's lines:

/// <summary>Newest orders first, one page at a time, with line count and total.</summary>
public static async Task<List<OrderSummary>> ListRecentAsync(ShopContext db, PageRequest page, CancellationToken ct = default)
{
    var orders = await db.Orders
        .OrderByDescending(o => o.PlacedAt)
        .ThenByDescending(o => o.Id)
        .Skip(page.Offset)
        .Take(page.Size)
        .Select(o => new { o.Id, CustomerName = o.Customer.Name, o.PlacedAt })
        .ToListAsync(ct);

    var result = new List<OrderSummary>();
    foreach (var order in orders)
    {
        var lines = await db.OrderLines.Where(l => l.OrderId == order.Id).ToListAsync(ct);
        result.Add(new OrderSummary(
            order.Id,
            order.CustomerName,
            order.PlacedAt,
            lines.Count,
            lines.Sum(l => l.Quantity * l.UnitPriceCents)));
    }

    return result;
}

Its new test, ListRecent_returns_line_count_and_total, checks the values and passes. All three ListRecent guards fail in the same run:

  Failed Shop.Tests.OrderQueryTests.ListRecent_tracks_nothing [9 ms]
   Assert.Empty() Failure: Collection was not empty
Collection: [OrderLine {Id: 239} Unchanged FK {OrderId: 120}, OrderLine {Id: 240} Unchanged FK {OrderId: 120}, OrderLine {Id: 159} Unchanged FK {OrderId: 80}, OrderLine {Id: 160} Unchanged FK {OrderId: 80}, OrderLine {Id: 79} Unchanged FK {OrderId: 40}, ···]
  Failed Shop.Tests.OrderQueryTests.ListRecent_sql_matches_snapshot [5 ms]
   SQL for ListRecent changed. Approved 1 command(s), received 11. First difference at line 1: approved "SELECT "o0"."Id", "c"."Name", "o0"."PlacedAt"", received "SELECT "o0"."Id", "c"."Name" AS "CustomerName", "o0"."PlacedAt"". Review ListRecent.received.sql against ListRecent.sql.
  Failed Shop.Tests.OrderQueryTests.ListRecent_stays_within_query_budget [3 ms]
   Assert.Equal() Failure: Values differ
Expected: 1
Actual:   11

Failed!  - Failed:     3, Passed:    11, Skipped:     0, Total:    14, Duration: 564 ms - Shop.Tests.dll (net10.0)

The 11 commands are 1 for the page and 10 for the lines, one per order. Tracking fails because those lines load as entities. The fix, in 569ebe7, computes both figures inside the same query:

/// <summary>Newest orders first, one page at a time, with line count and total computed by the database.</summary>
public static Task<List<OrderSummary>> ListRecentAsync(ShopContext db, PageRequest page, CancellationToken ct = default) =>
    db.Orders
        .OrderByDescending(o => o.PlacedAt)
        .ThenByDescending(o => o.Id)
        .Skip(page.Offset)
        .Take(page.Size)
        .Select(o => new OrderSummary(
            o.Id,
            o.Customer.Name,
            o.PlacedAt,
            o.Lines.Count,
            o.Lines.Sum(l => l.Quantity * l.UnitPriceCents)))
        .ToListAsync(ct);

Budget and tracking pass. The snapshot still fails, because the SQL did change: it now has two subqueries. Now it takes a person's review. In 569ebe7 it was approved in the same commit, and it's the SQL from the previous section:

-- 569ebe7, before the new snapshot was approved
  Failed Shop.Tests.OrderQueryTests.ListRecent_sql_matches_snapshot [4 ms]
   SQL for ListRecent changed. Approved 1 command(s), received 1. First difference at line 1: approved "SELECT "o0"."Id", "c"."Name", "o0"."PlacedAt"", received "SELECT "o0"."Id", "c"."Name", "o0"."PlacedAt", (". Review ListRecent.received.sql against ListRecent.sql.
Failed!  - Failed:     1, Passed:    13, Skipped:     0, Total:    14, Duration: 632 ms - Shop.Tests.dll (net10.0)

-- 569ebe7, after approval
Passed!  - Failed:     0, Passed:    14, Skipped:     0, Total:    14, Duration: 443 ms - Shop.Tests.dll (net10.0)

When EF Core's error suggests the shortcut

There's one case the rules don't stop. When a filter calls a local method, EF Core throws, and its message offers a way out:

H8 local method in Where: InvalidOperationException: The LINQ expression 'DbSet<Customer>() [...] .Where(c => Local.IsVip(c.Name))' could not be translated. Additional information: Translation of method 'Local.IsVip' failed. If this method can be mapped to your custom function, see https://go.microsoft.com/fwlink/?linkid=2132413 for more information. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.
H10 AsEnumerable before Where and Take: no exception, rows 5, commands 1, SQL: SELECT "o"."Id", "o"."CustomerId", "o"."PlacedAt" FROM "Orders" AS "o"

The first line is the error. The guide presents the way out it offers, client evaluation, as an option: "you can explicitly opt into client evaluation by calling methods like AsEnumerable or ToList". The second is what happens if you follow it and put AsEnumerable before the filter and the Take. There's no exception, one command is issued and the budget passes, but the SQL has no WHERE and no LIMIT: it reads the whole table and filters in memory. The snapshot catches it, because the text changed. Since this query loads tracked entities, the tracking check fails too; if you project before AsEnumerable or use AsNoTracking, the snapshot is all that's left.

The same goes for a local method in the final Select. EF Core allows it: "EF Core supports partial client evaluation in the top-level projection (essentially, the last call to Select())." So nothing throws. The snapshot sees it only if the SQL changes, for example when the method takes the whole entity; then the entity is tracked and the tracking check fails too.

The skill asks; CI or a Stop hook enforces

The repo's skill is 19 lines long and lives in .claude/skills/ef-query-guardrails/SKILL.md:

---
name: ef-query-guardrails
description: Run the EF Core query guardrails before handing over any change to LINQ queries, DbContext configuration, entities or anything under src/Shop. Use when you add or edit a query, a navigation, an Include, a projection or paging.
---

# EF Core query guardrails

Before you say the change is done:

1. Run `dotnet test` from the repository root.
2. If everything passes, report the summary line as printed (for example `Passed!  - Failed:     0, Passed:    15, ...`).
3. If a test fails, do not edit the test to make it pass. Report which guardrail failed and why:
   - `*_sql_matches_snapshot`: the SQL changed. Show the diff between `tests/Shop.Tests/Snapshots/<name>.sql` and `<name>.received.sql`. Never rename a `.received.sql` file yourself; a person approves new SQL.
   - `*_stays_within_query_budget`: the use case now sends a different number of commands. A count that grows with the page size is an N+1. Rewrite the query so the database does the work in one command; do not raise the budget constant.
   - `*_tracks_nothing`: a read now tracks entities. Project only scalar/value fields into a DTO, without embedding entity instances, or use AsNoTracking() when returning entities in read-only scenarios.
   - `RuleTests`: a fixed rule broke (Skip/Take without OrderBy, First without OrderBy or filter, a filter EF Core cannot translate, a page outside 1..100).
4. A new use case needs the same three tests, data that fills the page each test asks for, and a snapshot a person has reviewed.

This skill is a request, not a lock: the agent may skip it. This repository also runs the same `dotnet test` in CI (`.github/workflows/test.yml`) and in a Claude Code `Stop` hook of type `command` that exits with code 2 when the tests fail (`.claude/settings.json`), so the check does not depend on the agent. A person reviews every change to `Snapshots/` and to the budget constants.

Its last line warns that the agent may skip it. Claude Code applies it when it judges it relevant: "Claude uses skills when relevant, or you can invoke one directly with /skill-name." Nor does it stop an agent from renaming a .received.sql or raising a budget.

What enforces the check is running the same dotnet test outside the model, and the repo ships both ways: CI and a Stop hook. The .github/workflows/test.yml workflow runs it with -p:ContinuousIntegrationBuild=true on every push and pull request, but it only blocks a merge if branch protection requires it to pass. The Stop hook in .claude/settings.json runs it every time Claude tries to finish a turn:

{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "cd \"$CLAUDE_PROJECT_DIR\" && dotnet test 1>&2 || exit 2"
          }
        ]
      }
    ]
  }
}

The || exit 2 is what makes it binding. dotnet test exits with 1 when a test fails: "Failure. For example, one or more tests failed". For a hook, any exit code other than 0 or 2 is a non-blocking error, and Claude stops anyway. With 2, on a Stop hook: "Prevents Claude from stopping, continues the conversation". Claude Code still ends the turn after eight continuations in a row, but the count resets each time Claude calls a tool: while it keeps editing, the hook keeps it working until the tests pass. It can make them pass by changing the tests instead of the code, which is why changes to the tests need review too. The command uses bash syntax: on Windows, Claude Code runs hooks with Git Bash when it's installed; without it, it uses PowerShell, where this command fails and doesn't block. The workflow has run on GitHub on the published commit and passed. We didn't test the hook inside Claude Code: we ran its command in Git Bash, and it passed 15 of 15.

In every pull request, even when the tests pass, review the files in Snapshots/, the budget constants and any change to the tests or to ApplyRules: bad SQL can get in there without anything failing.

What this net doesn't cover

The other limits sit next to the piece they limit. Two remain:

  • Slow SQL. A command that fits the budget and matches the approved file can still be slow: the snapshot shows the text, not the execution plan.
  • Use cases without tests. The guards cover only the cases that have their three tests. A new method without them passes.

Frequently asked questions

Why not use Verify for the snapshots?

SqlSnapshot is 67 lines, comments included, with no dependency. Verify (MIT) does this and more, but it adds Verify, Argon, DiffEngine and SimpleInfoName to the test project. For one text file per use case, comparing strings was enough. If you need diff tools, value scrubbing or other kinds of snapshot, Verify is the better choice; we didn't test it here.

What budget do I set with Include?

Whatever the use case really needs. Without AsSplitQuery, an Include goes in a single command, like GetWithLines, whose budget is 1. With AsSplitQuery, it issued 2 commands on the bench, so that case would get a budget of 2. What matters is that the number doesn't grow with the page size.

Does the approved SQL hold for SQL Server or PostgreSQL?

No. Each provider generates its own SQL, and we only ran it on SQLite. SQLite is also a test double, and the testing strategy guide warns that even the results can differ: "The same LINQ query may return different results on different providers." Generate the snapshots with the provider you ship.

What ran and what didn't

.NET SDK 10.0.401, Microsoft.EntityFrameworkCore.Sqlite 10.0.14 and xunit 2.9.3, with in-memory SQLite. The data is 3 customers with 40 orders each and 1 to 3 lines per order, without Random. The history outputs come from those commits, with 14 tests; main runs 15, because a test for the First rule was added later. To see the failure in your copy: git checkout 43544d8 && dotnet test. No timings were measured. We didn't run any agent on the repo, so this post doesn't say how a specific agent responds to the skill.

Conclusion

A review that reads code, by a person or a model, can let an N+1 through with its test green. These three tests don't, as long as the page has rows: they check the SQL EF Core is about to execute, how many commands there are and what stays tracked.

Pick the read use case your project hits most today. Add the counter and a budget, seed data that fills its page, approve its current SQL and put dotnet test in CI. The next change that issues more commands will fail in CI; make it a required check on the branch and it won't reach the merge.

References

Subscribe

Get the latest posts delivered right to your inbox.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Comments

No comments yet. Be the first to share your thoughts!

Subscribed!

Registered! A confirmation link has been sent to your email address. If you don't see it, please check your spam folder.

Error

An error occurred. Please try again.

Full code