<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/"><channel><title>Architecture on Russell ‛Russ’ Frith</title><link>https://russfrith.com/tags/architecture/</link><description>Recent content in Architecture on Russell ‛Russ’ Frith</description><generator>Hugo</generator><language>en-us</language><lastBuildDate>Tue, 17 Nov 2026 16:28:17 -0500</lastBuildDate><atom:link href="https://russfrith.com/tags/architecture/index.xml" rel="self" type="application/rss+xml"/><item><title>In Defense of the Repository: Constrained, Specification-Driven, and Tunable</title><link>https://russfrith.com/posts/repository-pattern-ef-core-specifications/</link><pubDate>Tue, 17 Nov 2026 16:28:17 -0500</pubDate><guid>https://russfrith.com/posts/repository-pattern-ef-core-specifications/</guid><description>Why a narrow, enforced repository is still worth having over coding directly against EF Core&amp;#39;s DbContext, with a five-way comparison and real numbers</description><content:encoded><![CDATA[<p>Many, dare I say most, .NET developers argue against the Repository Pattern when using Entity Framework Core (EF Core). A <code>DbContext</code> is already a unit of work. A <code>DbSet&lt;T&gt;</code> is already an <code>IQueryable&lt;T&gt;</code>, which is already a repository and a specification mechanism rolled into one, courtesy of LINQ. That&rsquo;s the honest, strong version of the argument against adding a repository layer on top of EF Core, and the people making it aren&rsquo;t wrong about the common failure mode: a repository with <code>GetAll()</code>, a dozen near-duplicate <code>GetByXAsync()</code> methods, or one that just hands back <code>IQueryable&lt;T&gt;</code> and calls it abstraction. That kind of repository adds a file; it doesn&rsquo;t do anything a plain <code>DbSet</code> doesn&rsquo;t already do.</p>
<p>My position is narrower than &ldquo;repositories are good.&rdquo; It&rsquo;s that a repository earns its keep specifically when it&rsquo;s a <em>narrow, enforced seam</em>, not a general-purpose wrapper around <code>DbContext</code>. I&rsquo;m borrowing &ldquo;seam&rdquo; from Michael Feathers&rsquo; <em>Working Effectively with Legacy Code</em>, where he defines it as <a href="https://martinfowler.com/bliki/LegacySeam.html">a place where you can alter behavior in a program without editing in that place</a>, which is exactly what a named repository method, a specification, or a query object gives you over inline LINQ: somewhere to swap the real implementation without touching every caller. A narrower contract is easier to read, test, tune, and enforce than the full surface of <code>DbContext</code> itself. Without that enforcement, nothing stops a query from reaching straight past the aggregate root: a <code>DbSet&lt;OrderLine&gt;</code> looks like any other simple, convenient LINQ query, and it&rsquo;s just as easy to write one that mutates a line&rsquo;s quantity directly, outside <code>Order</code>&rsquo;s own invariants, as it is to write one that respects them. A named repository method, a specification object, and a per-use-case query object are all the same underlying idea: a named query contract with a swappable implementation behind it. The question worth arguing about isn&rsquo;t &ldquo;repository or no repository,&rdquo; it&rsquo;s &ldquo;how narrow is the contract, and what enforces it.&rdquo; This post builds the same small scenario five ways, including the two &ldquo;no repository&rdquo; versions written the way their proponents would actually write them, and reports where the constrained version wins, where it loses, and where the numbers are more modest than the pitch.</p>
<p>Everything below is pulled directly from  a runnable .NET 10 / PostgreSQL 17 solution. I&rsquo;ll flag every number as measured, and where I measured something only once, on one machine, I&rsquo;ll say so rather than imply more than it proves.</p>
<h2 id="the-honest-case-against-repositories">The honest case against repositories</h2>
<p>Here&rsquo;s the strongest version of the argument, stated the way I think its proponents would want it stated, not strawmanned:</p>
<ul>
<li><strong><code>DbContext</code> already is a unit of work.</strong> <code>SaveChangesAsync()</code> commits everything staged against it in one transaction. Wrapping it in <code>IUnitOfWork.SaveChangesAsync()</code> doesn&rsquo;t add a capability; it adds a layer of indirection over a capability EF Core already gives you for free.</li>
<li><strong><code>DbSet&lt;T&gt;</code> already is a repository, and a better one than most hand-rolled ones.</strong> It supports <code>Add</code>, <code>Remove</code>, <code>Find</code>, and the full range of LINQ querying, all backed by an API surface that&rsquo;s been tested across more production workloads than a bespoke interface ever will be.</li>
<li><strong>LINQ-to-Entities already is a specification mechanism.</strong> <code>Where(predicate)</code> composed with <code>Include(nav)</code> and <code>OrderBy(key)</code> is exactly what a specification object re-expresses with more ceremony: a filter, a shape, an order, expressed as data instead of as an inline expression. It&rsquo;s arguably a more elegant mechanism than any specification could be, too: satisfying <code>IQueryable&lt;T&gt;</code>&rsquo;s provider contract (translating arbitrary expression trees into SQL) is a genuinely hard problem, but once a provider exists, the queries written against it are about as simple as query syntax gets. A hand-rolled <code>ISpecification&lt;T&gt;</code> only has to be as expressive as the cases its author anticipated; <code>IQueryable&lt;T&gt;</code> already handles whatever the provider author chose to support, which is most of what SQL can do.</li>
<li><strong>An extra layer is an extra thing to maintain</strong>, for a case most apps don&rsquo;t actually hit: swapping the ORM. Nobody swaps EF Core for something else mid-project, and if they did, the repository wouldn&rsquo;t save them, because the repository&rsquo;s <code>ISpecification&lt;T&gt;</code> implementation is usually still built around <code>IQueryable</code>-shaped thinking anyway. </li>
</ul>
<p>I think this argument is correct about what it&rsquo;s correct about. It&rsquo;s an argument against <em>unconstrained</em> repositories: ones with no enforced boundary, where <code>IQueryable&lt;T&gt;</code> or <code>DbSet&lt;T&gt;</code> itself leaks past the interface, or where the &ldquo;repository&rdquo; is really just <code>DbContext</code> with a thinner name. It is not, in my view, an argument against <em>any</em> seam between application code and persistence code. The disagreement is about where the premises land, not about who&rsquo;s reading the EF Core docs correctly.</p>
<h2 id="five-ways-to-do-the-same-thing">Five ways to do the same thing</h2>
<p>The scenario: <strong>get a customer&rsquo;s open orders, submit the first draft one.</strong> &ldquo;Open&rdquo; means <code>Draft</code> or <code>Submitted</code>, defined once on the <code>Order</code> aggregate itself so nothing downstream has to redefine it:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-csharp" data-lang="csharp"><span style="display:flex;"><span><span style="color:#66d9ef">namespace</span> RepositoryPattern.Domain;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">Order</span> : IAggregateRoot
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// The statuses an order is still &#34;in flight&#34; under. Defined once here so</span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// both the domain&#39;s own checks and query specifications stay in sync.</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">static</span> <span style="color:#66d9ef">readonly</span> OrderStatus[] OpenStatuses = [OrderStatus.Draft, OrderStatus.Submitted];
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">readonly</span> List&lt;OrderLine&gt; _lines = [];
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> Guid Id { <span style="color:#66d9ef">get</span>; <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">set</span>; }
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> Guid CustomerId { <span style="color:#66d9ef">get</span>; <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">set</span>; }
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> OrderStatus Status { <span style="color:#66d9ef">get</span>; <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">set</span>; }
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> DateTimeOffset CreatedAt { <span style="color:#66d9ef">get</span>; <span style="color:#66d9ef">private</span> <span style="color:#66d9ef">set</span>; }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> IReadOnlyCollection&lt;OrderLine&gt; Lines =&gt; _lines;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">bool</span> IsOpen =&gt; OpenStatuses.Contains(Status);
</span></span></code></pre></div><p>I built the same scenario five times: the two &ldquo;skip the repository&rdquo; versions written the way their proponents would write them, a classic named-method repository, a specification-driven repository, and the constrained hybrid this post argues for.</p>
<p><strong>Option 1: raw <code>DbContext</code>.</strong> The simplest of the five, and the one the honest case above describes:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-csharp" data-lang="csharp"><span style="display:flex;"><span><span style="color:#66d9ef">using</span> Microsoft.EntityFrameworkCore;
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">using</span> RepositoryPattern.Comparisons.Shared;
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">using</span> RepositoryPattern.Domain;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">namespace</span> RepositoryPattern.Comparisons.Option1_RawDbContext;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Option 1: DbContext used directly in the handler, written the way its</span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// proponents recommend it - no repository, no query object, EF Core&#39;s LINQ</span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// provider and change tracking used as-is. This is the simplest of the five.</span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">OpenOrdersScenario</span>(ComparisonDbContext dbContext)
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">async</span> Task&lt;Order?&gt; GetOpenOrdersAndSubmitOneAsync(Guid customerId, CancellationToken cancellationToken)
</span></span><span style="display:flex;"><span>    {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">var</span> openOrders = <span style="color:#66d9ef">await</span> dbContext.Orders
</span></span><span style="display:flex;"><span>            .Include(order =&gt; order.Lines)
</span></span><span style="display:flex;"><span>            .Where(order =&gt; order.CustomerId == customerId &amp;&amp; Order.OpenStatuses.Contains(order.Status))
</span></span><span style="display:flex;"><span>            .OrderByDescending(order =&gt; order.CreatedAt)
</span></span><span style="display:flex;"><span>            .ToListAsync(cancellationToken);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">var</span> orderToSubmit = openOrders.FirstOrDefault(order =&gt; order.Status == OrderStatus.Draft);
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">if</span> (orderToSubmit <span style="color:#66d9ef">is</span> <span style="color:#66d9ef">null</span>)
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">null</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        orderToSubmit.Submit();
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">await</span> dbContext.SaveChangesAsync(cancellationToken);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> orderToSubmit;
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p><strong>Option 5: the constrained hybrid.</strong> Same scenario, against the actual production <code>IOrderRepository</code> and <code>IUnitOfWork</code>, not a stand-in built for this comparison:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-csharp" data-lang="csharp"><span style="display:flex;"><span><span style="color:#66d9ef">using</span> RepositoryPattern.Application.Abstractions;
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">using</span> RepositoryPattern.Domain;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">namespace</span> RepositoryPattern.Comparisons.Option5_ConstrainedHybrid;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Option 5: the constrained hybrid this post defends. Unlike options 1-4,</span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// this isn&#39;t a smaller stand-in built for the comparison - it&#39;s the actual</span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// production IOrderRepository and IUnitOfWork from Application/Infrastructure,</span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// wired up the same way the Api project wires them up.</span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">SubmitOpenOrderHandler</span>(IOrderRepository orderRepository, IUnitOfWork unitOfWork)
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">async</span> Task&lt;Order?&gt; HandleAsync(Guid customerId, CancellationToken cancellationToken)
</span></span><span style="display:flex;"><span>    {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">var</span> openOrders = <span style="color:#66d9ef">await</span> orderRepository.GetOpenOrdersForCustomerAsync(customerId, cancellationToken);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">var</span> orderToSubmit = openOrders.FirstOrDefault(order =&gt; order.Status == OrderStatus.Draft);
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">if</span> (orderToSubmit <span style="color:#66d9ef">is</span> <span style="color:#66d9ef">null</span>)
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">null</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        orderToSubmit.Submit();
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">await</span> unitOfWork.SaveChangesAsync(cancellationToken);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> orderToSubmit;
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>Read those two side by side and the handler bodies are nearly identical. The difference is entirely in what each one is built on top of, not in what it does. That&rsquo;s the whole argument in a nutshell: options 1 and 5 look almost the same at the call site, and all the honest cost of option 5 is hidden one layer down, in scaffolding that doesn&rsquo;t exist for option 1 at all.</p>
<p>Here&rsquo;s the comparison, measured from the actual code in the repository (file and line counts via <code>Get-ChildItem | Measure-Object -Line</code>, excluding generated migrations and the <code>Shared</code>/<code>ComparisonDbContext</code> helper options 1-4 lean on). All five return aggregates, never an <code>IQueryable</code> or a DTO, so that row isn&rsquo;t worth a column of its own:</p>
<table>
  <thead>
      <tr>
          <th></th>
          <th>Option 1: raw <code>DbContext</code></th>
          <th>Option 2: query objects</th>
          <th>Option 3: classic repository</th>
          <th>Option 4: spec repository</th>
          <th>Option 5: constrained hybrid</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td>Files / lines (the option&rsquo;s own code)</td>
          <td>1 file, 24 lines</td>
          <td>3 files, 41 lines</td>
          <td>4 files, 49 lines</td>
          <td>3 files, 51 lines</td>
          <td>1 file, 20 lines</td>
      </tr>
      <tr>
          <td>Constrained to aggregate roots?</td>
          <td>no, any entity</td>
          <td>yes (via a thin <code>AggregateQueryObject&lt;TAggregate&gt;</code> base, compiler-enforced)</td>
          <td>yes (via a thin <code>AggregateRepository&lt;TAggregate&gt;</code> base, compiler-enforced)</td>
          <td>yes (<code>T : class, IAggregateRoot</code>, compiler-enforced)</td>
          <td>yes (<code>T : class, IAggregateRoot</code>, compiler-enforced)</td>
      </tr>
      <tr>
          <td><code>SaveChanges</code> / commit</td>
          <td>on <code>DbContext</code>, called from the handler</td>
          <td>on <code>DbContext</code>, called from the handler</td>
          <td>on the repository itself</td>
          <td>on the repository itself</td>
          <td>on a separate <code>IUnitOfWork</code> only</td>
      </tr>
      <tr>
          <td>Unit-testable without a database</td>
          <td>no</td>
          <td>no</td>
          <td>no</td>
          <td>yes</td>
          <td>yes</td>
      </tr>
  </tbody>
</table>
<p>Four more criteria matter here, but their real answers are full sentences, not short table cells, so here they are per option instead of wrapped into a narrow column:</p>
<p><strong>Option 1: raw <code>DbContext</code></strong></p>
<ul>
<li>Contract lives inline in the LINQ, in the handler.</li>
<li>Tuning: rewrite the LINQ in place; nothing stops a second use case from copy-pasting a slightly different version.</li>
<li>What breaks first: nothing structural, just discipline.</li>
<li>Testability: no, <code>DbContext</code> only translates queries against an actual provider.</li>
</ul>
<p><strong>Option 2: query objects</strong></p>
<ul>
<li>Contract lives in the query object&rsquo;s <code>ExecuteAsync</code>.</li>
<li>Tuning: same as option 1, but at least isolated to one class.</li>
<li>What breaks first: nothing structural either.</li>
<li>Testability: no, same reason as option 1, one level removed.</li>
</ul>
<p><strong>Option 3: classic repository</strong></p>
<ul>
<li>Contract lives in the repository interface&rsquo;s method name.</li>
<li>Tuning: swap the interface&rsquo;s implementation; still ad hoc inside it.</li>
<li>What breaks first: duplicate near-identical repository methods across aggregates.</li>
<li>Testability: no. Mocking the interface lets you test the <em>handler</em> in isolation, but the query itself still needs EF Core and a real database to prove correct.</li>
</ul>
<p><strong>Option 4: spec repository</strong></p>
<ul>
<li>Contract lives in the <code>ISpecification&lt;T&gt;</code> object.</li>
<li>Tuning: swap the generic repository&rsquo;s evaluator for everyone, or bypass the abstraction entirely; there&rsquo;s no hook for &ldquo;just this one query.&rdquo;</li>
<li>What breaks first: a new aggregate needs its own hand-written implementation class, since there&rsquo;s no open-generic registration doing that for free; and there&rsquo;s still no hook for tuning just one query.</li>
<li>Testability: yes. <code>OpenOrdersForCustomer.Criteria</code> is a plain <code>Expression&lt;Func&lt;Order,bool&gt;&gt;</code>, compiled and run against in-memory objects, no database involved.</li>
</ul>
<p><strong>Option 5: constrained hybrid</strong></p>
<ul>
<li>Contract lives in both: <code>IOrderRepository</code>&rsquo;s method <strong>and</strong> <code>OpenOrdersForCustomer</code>, pinned equal by a contract test.</li>
<li>Tuning: add exactly one named method with its own tuned implementation; every other query keeps using the generic spec path.</li>
<li>What breaks first: the ceremony itself. A new aggregate needs an interface, maybe a derived class, and a DI registration before anyone can query it.</li>
<li>Testability: yes, same spec and the same test as option 4, plus a contract test proving the tuned path returns identical results.</li>
</ul>
<p>Notice the row I almost led with and then didn&rsquo;t: &ldquo;files / lines.&rdquo; Option 5&rsquo;s own code is the smallest in the table, 20 lines. That&rsquo;s a misleading way to frame it. It&rsquo;s sitting on top of 285 lines of shared scaffolding that options 1-4 don&rsquo;t need at all for a single query. If this app only ever needed this one query against this one aggregate, option 1 wins outright, and it isn&rsquo;t close. The honest framing is &ldquo;cheap once the scaffolding exists, expensive the first time,&rdquo; not &ldquo;fewer lines.&rdquo; The same shape shows up more clearly as a picture than as a table row:</p>
<p><img alt="Horizontal stacked bar chart of lines of code per option. Option 1, raw DbContext: 24 lines, all its own. Option 2, query objects: 41 lines, all its own. Option 3, classic repository: 49 lines, all its own. Option 4, specification repository: 51 lines of its own plus 106 lines of shared Application scaffolding, 157 total, with no Infrastructure reuse since its repository is a stand-in built for the comparison. Option 5, constrained hybrid: 20 lines of its own plus the same 106 lines of shared Application scaffolding plus 179 lines of shared Infrastructure scaffolding only it reuses, 305 total, since it&rsquo;s the actual production repository." loading="lazy" src="/posts/repository-pattern-ef-core-specifications/lines-of-code-comparison.svg"></p>
<h2 id="the-key-insight-and-its-caveat">The key insight, and its caveat</h2>
<p>A repository method, a specification, and a query object are the same idea wearing different clothes: a named contract for a query, with a swappable implementation behind the name. <code>GetOpenOrdersForCustomerAsync</code> is a name. <code>OpenOrdersForCustomer</code> is a name. <code>GetOpenOrdersForCustomer.ExecuteAsync</code> is a name. All three say &ldquo;here&rsquo;s what this query means,&rdquo; not &ldquo;here&rsquo;s how to write any query you want.&rdquo;</p>
<p>The caveat worth calling out: <strong>only the specification is unit-testable without a database</strong>, and the reason is structural, not incidental. A query object and a named repository method are both <em>code that executes a query</em>; proving they&rsquo;re correct means running them against something that can actually execute LINQ-to-Entities or SQL, which means a real provider and (for anything beyond the most trivial translation) a real database. A specification is different in kind: it&rsquo;s an inert data object whose <code>Criteria</code> is a plain <code>Expression&lt;Func&lt;T, bool&gt;&gt;</code>. You can <code>.Compile()</code> it and run it against in-memory objects, because it&rsquo;s not an executing query at all, it&rsquo;s a description of one:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-csharp" data-lang="csharp"><span style="display:flex;"><span><span style="color:#a6e22e">    [Fact]</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">void</span> OpenOrdersForCustomer_criteria_matches_draft_and_submitted_only()
</span></span><span style="display:flex;"><span>    {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">var</span> customerId = Guid.NewGuid();
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">var</span> spec = <span style="color:#66d9ef">new</span> OpenOrdersForCustomer(customerId);
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">var</span> predicate = spec.Criteria!.Compile();
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">var</span> draft = Order.Create(customerId);
</span></span><span style="display:flex;"><span>        draft.AddLine(<span style="color:#e6db74">&#34;Widget&#34;</span>, <span style="color:#ae81ff">1</span>, <span style="color:#ae81ff">9.99</span>m);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">var</span> submitted = Order.Create(customerId);
</span></span><span style="display:flex;"><span>        submitted.AddLine(<span style="color:#e6db74">&#34;Widget&#34;</span>, <span style="color:#ae81ff">1</span>, <span style="color:#ae81ff">9.99</span>m);
</span></span><span style="display:flex;"><span>        submitted.Submit();
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">var</span> shipped = Order.Create(customerId);
</span></span><span style="display:flex;"><span>        shipped.AddLine(<span style="color:#e6db74">&#34;Widget&#34;</span>, <span style="color:#ae81ff">1</span>, <span style="color:#ae81ff">9.99</span>m);
</span></span><span style="display:flex;"><span>        shipped.Submit();
</span></span><span style="display:flex;"><span>        shipped.Ship();
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">var</span> otherCustomer = Order.Create(Guid.NewGuid());
</span></span><span style="display:flex;"><span>        otherCustomer.AddLine(<span style="color:#e6db74">&#34;Widget&#34;</span>, <span style="color:#ae81ff">1</span>, <span style="color:#ae81ff">9.99</span>m);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        Assert.True(predicate(draft));
</span></span><span style="display:flex;"><span>        Assert.True(predicate(submitted));
</span></span><span style="display:flex;"><span>        Assert.False(predicate(shipped));
</span></span><span style="display:flex;"><span>        Assert.False(predicate(otherCustomer));
</span></span><span style="display:flex;"><span>    }
</span></span></code></pre></div><p>No database, no <code>DbContext</code>, no test container. That&rsquo;s a genuine, narrow advantage specifications have over the other two shapes in the table, and it&rsquo;s the sharpest practical argument for specifications <em>specifically</em>, not just for &ldquo;constrained repositories in general.&rdquo;</p>
<p>The caveat on the caveat: this test proves the <em>predicate&rsquo;s logic</em> is right. It says nothing about whether EF Core&rsquo;s query translator turns that same expression into the SQL you think it does. Those are different failure modes, and only an integration test against a real provider catches the second one. The contract tests later in this post exist for exactly that gap.</p>
<h2 id="the-design">The design</h2>
<p>Four pieces make this version constrained, not just a differently-named copy of an unconstrained one.</p>
<p><strong>A marker interface restricts what can get a repository at all.</strong> <code>OrderLine</code> is part of the <code>Order</code> aggregate, but it never gets its own repository, because repository interfaces are generically constrained to <code>IAggregateRoot</code>:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-csharp" data-lang="csharp"><span style="display:flex;"><span><span style="color:#66d9ef">namespace</span> RepositoryPattern.Domain;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Marker interface. Repository interfaces constrain T to this, so only</span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// aggregate roots (Order) can ever get a repository, not their children (OrderLine).</span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">interface</span> <span style="color:#a6e22e">IAggregateRoot</span>;
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-csharp" data-lang="csharp"><span style="display:flex;"><span><span style="color:#66d9ef">using</span> RepositoryPattern.Application.Specifications;
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">using</span> RepositoryPattern.Domain;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">namespace</span> RepositoryPattern.Application.Abstractions;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">interface</span> <span style="color:#a6e22e">IReadRepository</span>&lt;T&gt; <span style="color:#66d9ef">where</span> T : class, IAggregateRoot
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    Task&lt;T?&gt; GetByIdAsync(Guid id, CancellationToken cancellationToken);
</span></span><span style="display:flex;"><span>    Task&lt;T?&gt; FirstOrDefaultAsync(ISpecification&lt;T&gt; specification, CancellationToken cancellationToken);
</span></span><span style="display:flex;"><span>    Task&lt;List&lt;T&gt;&gt; ListAsync(ISpecification&lt;T&gt; specification, CancellationToken cancellationToken);
</span></span><span style="display:flex;"><span>    Task&lt;<span style="color:#66d9ef">bool</span>&gt; AnyAsync(ISpecification&lt;T&gt; specification, CancellationToken cancellationToken);
</span></span><span style="display:flex;"><span>    Task&lt;<span style="color:#66d9ef">int</span>&gt; CountAsync(ISpecification&lt;T&gt; specification, CancellationToken cancellationToken);
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-csharp" data-lang="csharp"><span style="display:flex;"><span><span style="color:#66d9ef">using</span> RepositoryPattern.Domain;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">namespace</span> RepositoryPattern.Application.Abstractions;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">interface</span> <span style="color:#a6e22e">IRepository</span>&lt;T&gt; : IReadRepository&lt;T&gt; <span style="color:#66d9ef">where</span> T : class, IAggregateRoot
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">void</span> Add(T entity);
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">void</span> Remove(T entity);
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>No <code>GetAll()</code>. No <code>Update()</code>, since a tracked aggregate&rsquo;s changes are already staged; calling <code>Update</code> on it would be a no-op dressed up as an action. No <code>SaveChanges()</code> on the repository itself, that lives on a separate unit of work:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-csharp" data-lang="csharp"><span style="display:flex;"><span><span style="color:#66d9ef">namespace</span> RepositoryPattern.Application.Abstractions;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Repositories never save; only a unit of work commits. That keeps &#34;stage a</span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// change&#34; and &#34;commit the transaction&#34; as separate decisions, which matters</span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// once a use case touches more than one aggregate.</span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">interface</span> <span style="color:#a6e22e">IUnitOfWork</span>
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    Task&lt;<span style="color:#66d9ef">int</span>&gt; SaveChangesAsync(CancellationToken cancellationToken);
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>And no <code>IQueryable&lt;T&gt;</code> or <code>Expression</code> returned to a caller anywhere on these interfaces: <code>GetByIdAsync</code>, <code>FirstOrDefaultAsync</code>, <code>ListAsync</code>, <code>AnyAsync</code>, <code>CountAsync</code> all return the aggregate itself, or a primitive. This is the actual difference from the straw-man repository the honest case against repositories is arguing against. A repository with <code>IQueryable&lt;T&gt; Orders { get; }</code> isn&rsquo;t a seam, it&rsquo;s <code>DbContext</code> with a different name:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-csharp" data-lang="csharp"><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">interface</span> <span style="color:#a6e22e">IOrderRepository</span>
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    IQueryable&lt;Order&gt; Orders { <span style="color:#66d9ef">get</span>; } <span style="color:#75715e">// leaks EF Core&#39;s query provider past the interface</span>
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>I&rsquo;m not implementing that version; nobody I&rsquo;m aware of actually recommends it. It&rsquo;s here only to show what this post is <em>not</em> defending. The problem isn&rsquo;t the style of the method signature, it&rsquo;s that every caller now depends on whatever <code>DbContext</code> is behind <code>Orders</code>. The interface stops being a contract at all; the real contract becomes &ldquo;whatever LINQ-to-Entities can translate,&rdquo; which is an EF Core concept wearing an application-layer name.</p>
<p><strong>The specification is its own small contract</strong>, no projections, criteria and shape only:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-csharp" data-lang="csharp"><span style="display:flex;"><span><span style="color:#66d9ef">using</span> System.Linq.Expressions;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">namespace</span> RepositoryPattern.Application.Specifications;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Our own, minimal specification contract: criteria, includes, ordering, paging,</span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// a tracking flag. No projections - a spec always describes how to fetch an</span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// aggregate, never a DTO shape.</span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">interface</span> <span style="color:#a6e22e">ISpecification</span>&lt;T&gt;
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    Expression&lt;Func&lt;T, <span style="color:#66d9ef">bool</span>&gt;&gt;? Criteria { <span style="color:#66d9ef">get</span>; }
</span></span><span style="display:flex;"><span>    List&lt;Expression&lt;Func&lt;T, <span style="color:#66d9ef">object</span>&gt;&gt;&gt; Includes { <span style="color:#66d9ef">get</span>; }
</span></span><span style="display:flex;"><span>    Expression&lt;Func&lt;T, <span style="color:#66d9ef">object</span>&gt;&gt;? OrderBy { <span style="color:#66d9ef">get</span>; }
</span></span><span style="display:flex;"><span>    Expression&lt;Func&lt;T, <span style="color:#66d9ef">object</span>&gt;&gt;? OrderByDescending { <span style="color:#66d9ef">get</span>; }
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">int?</span> Skip { <span style="color:#66d9ef">get</span>; }
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">int?</span> Take { <span style="color:#66d9ef">get</span>; }
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">bool</span> IsPagingEnabled { <span style="color:#66d9ef">get</span>; }
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">bool</span> AsNoTracking { <span style="color:#66d9ef">get</span>; }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>Paging requires an ordering, enforced in the base class rather than left as a convention:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-csharp" data-lang="csharp"><span style="display:flex;"><span>    <span style="color:#66d9ef">protected</span> <span style="color:#66d9ef">void</span> ApplyPaging(<span style="color:#66d9ef">int</span> skip, <span style="color:#66d9ef">int</span> take)
</span></span><span style="display:flex;"><span>    {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">if</span> (OrderBy <span style="color:#66d9ef">is</span> <span style="color:#66d9ef">null</span> &amp;&amp; OrderByDescending <span style="color:#66d9ef">is</span> <span style="color:#66d9ef">null</span>)
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">throw</span> <span style="color:#66d9ef">new</span> InvalidOperationException(<span style="color:#e6db74">&#34;Paging requires an ordering to be applied first.&#34;</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        Skip = skip;
</span></span><span style="display:flex;"><span>        Take = take;
</span></span><span style="display:flex;"><span>        IsPagingEnabled = <span style="color:#66d9ef">true</span>;
</span></span><span style="display:flex;"><span>    }
</span></span></code></pre></div><p>A named spec is just that base class, specialized:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-csharp" data-lang="csharp"><span style="display:flex;"><span><span style="color:#66d9ef">using</span> RepositoryPattern.Domain;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">namespace</span> RepositoryPattern.Application.Specifications;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// The behavioral definition of &#34;a customer&#39;s open orders&#34;. The repository&#39;s</span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// tuned, hand-written-SQL path is asserted to return exactly the same rows,</span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// in exactly the same order, as this spec - see the contract tests.</span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">sealed</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">OpenOrdersForCustomer</span> : Specification&lt;Order&gt;
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> OpenOrdersForCustomer(Guid customerId)
</span></span><span style="display:flex;"><span>        : <span style="color:#66d9ef">base</span>(order =&gt; order.CustomerId == customerId &amp;&amp; Order.OpenStatuses.Contains(order.Status))
</span></span><span style="display:flex;"><span>    {
</span></span><span style="display:flex;"><span>        AddInclude(order =&gt; order.Lines);
</span></span><span style="display:flex;"><span>        ApplyOrderByDescending(order =&gt; order.CreatedAt);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p><strong>One evaluator turns a spec into an EF Core query.</strong> This is the only place <code>Include</code>, <code>Where</code>, <code>OrderBy</code>, and <code>AsNoTracking</code> get called against a spec; specs themselves never see EF Core:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-csharp" data-lang="csharp"><span style="display:flex;"><span><span style="color:#66d9ef">using</span> Microsoft.EntityFrameworkCore;
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">using</span> RepositoryPattern.Application.Specifications;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">namespace</span> RepositoryPattern.Infrastructure.Persistence;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// The one place that knows how to turn an ISpecification&lt;T&gt; into an EF Core</span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// query. Specs themselves stay free of EF Core concepts; this class is where</span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Include(), Where(), OrderBy() and AsNoTracking() actually get called.</span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">internal</span> <span style="color:#66d9ef">static</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">SpecificationEvaluator</span>
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">static</span> IQueryable&lt;T&gt; Apply&lt;T&gt;(IQueryable&lt;T&gt; query, ISpecification&lt;T&gt; specification) <span style="color:#66d9ef">where</span> T : <span style="color:#66d9ef">class</span>
</span></span><span style="display:flex;"><span>    {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">if</span> (specification.Criteria <span style="color:#66d9ef">is</span> not <span style="color:#66d9ef">null</span>)
</span></span><span style="display:flex;"><span>            query = query.Where(specification.Criteria);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        query = specification.Includes.Aggregate(query, (current, include) =&gt; current.Include(include));
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">if</span> (specification.OrderBy <span style="color:#66d9ef">is</span> not <span style="color:#66d9ef">null</span>)
</span></span><span style="display:flex;"><span>            query = query.OrderBy(specification.OrderBy);
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">else</span> <span style="color:#66d9ef">if</span> (specification.OrderByDescending <span style="color:#66d9ef">is</span> not <span style="color:#66d9ef">null</span>)
</span></span><span style="display:flex;"><span>            query = query.OrderByDescending(specification.OrderByDescending);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">if</span> (specification.IsPagingEnabled)
</span></span><span style="display:flex;"><span>            query = query.Skip(specification.Skip!.Value).Take(specification.Take!.Value);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">if</span> (specification.AsNoTracking)
</span></span><span style="display:flex;"><span>            query = query.AsNoTracking();
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> query;
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p><strong><code>EfRepository&lt;T&gt;</code> is concrete, not abstract, registered once as an open generic</strong>, so an aggregate with no named queries needs no class of its own:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-csharp" data-lang="csharp"><span style="display:flex;"><span><span style="color:#66d9ef">using</span> Microsoft.EntityFrameworkCore;
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">using</span> RepositoryPattern.Application.Abstractions;
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">using</span> RepositoryPattern.Application.Specifications;
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">using</span> RepositoryPattern.Domain;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">namespace</span> RepositoryPattern.Infrastructure.Persistence;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Concrete, not abstract: an aggregate with no named queries needs no class</span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// of its own - it&#39;s registered as an open generic (see ServiceCollectionExtensions).</span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// An aggregate with named methods derives from this and adds them (see OrderRepository).</span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">//</span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Deliberately NOT abstract, and deliberately exposing no DbSet/IQueryable/DbContext</span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// as protected members - see ComposeWithRawSql, the one narrow exception, and</span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// FINDINGS.md for why.</span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">internal</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">EfRepository</span>&lt;T&gt;(OrderingDbContext dbContext) : IRepository&lt;T&gt; <span style="color:#66d9ef">where</span> T : class, IAggregateRoot
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">async</span> Task&lt;T?&gt; GetByIdAsync(Guid id, CancellationToken cancellationToken)
</span></span><span style="display:flex;"><span>        =&gt; <span style="color:#66d9ef">await</span> dbContext.Set&lt;T&gt;().FindAsync([id], cancellationToken);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">async</span> Task&lt;T?&gt; FirstOrDefaultAsync(ISpecification&lt;T&gt; specification, CancellationToken cancellationToken)
</span></span><span style="display:flex;"><span>        =&gt; <span style="color:#66d9ef">await</span> ApplySpecification(specification).FirstOrDefaultAsync(cancellationToken);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">async</span> Task&lt;List&lt;T&gt;&gt; ListAsync(ISpecification&lt;T&gt; specification, CancellationToken cancellationToken)
</span></span><span style="display:flex;"><span>        =&gt; <span style="color:#66d9ef">await</span> ApplySpecification(specification).ToListAsync(cancellationToken);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">async</span> Task&lt;<span style="color:#66d9ef">bool</span>&gt; AnyAsync(ISpecification&lt;T&gt; specification, CancellationToken cancellationToken)
</span></span><span style="display:flex;"><span>        =&gt; <span style="color:#66d9ef">await</span> ApplySpecification(specification).AnyAsync(cancellationToken);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">async</span> Task&lt;<span style="color:#66d9ef">int</span>&gt; CountAsync(ISpecification&lt;T&gt; specification, CancellationToken cancellationToken)
</span></span><span style="display:flex;"><span>        =&gt; <span style="color:#66d9ef">await</span> ApplySpecification(specification).CountAsync(cancellationToken);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">void</span> Add(T entity) =&gt; dbContext.Set&lt;T&gt;().Add(entity);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">void</span> Remove(T entity) =&gt; dbContext.Set&lt;T&gt;().Remove(entity);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">private</span> IQueryable&lt;T&gt; ApplySpecification(ISpecification&lt;T&gt; specification)
</span></span><span style="display:flex;"><span>        =&gt; SpecificationEvaluator.Apply(dbContext.Set&lt;T&gt;(), specification);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// The one protected member the base class exposes: a derived, named-method</span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// repository (OrderRepository) can compose a hand-written SQL fragment with</span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// Include()/ordering from a spec, without ever seeing a bare DbSet or IQueryable.</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">protected</span> IQueryable&lt;T&gt; ComposeWithRawSql(FormattableString sql, ISpecification&lt;T&gt;? specification = <span style="color:#66d9ef">null</span>)
</span></span><span style="display:flex;"><span>    {
</span></span><span style="display:flex;"><span>        IQueryable&lt;T&gt; query = dbContext.Set&lt;T&gt;().FromSqlInterpolated(sql);
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> specification <span style="color:#66d9ef">is</span> <span style="color:#66d9ef">null</span> ? query : SpecificationEvaluator.Apply(query, specification);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>That <code>ComposeWithRawSql</code> method is the base class&rsquo;s only extension point, and it earned its current shape the hard way. My first attempt exposed a plain <code>protected IQueryable&lt;T&gt; ApplySpecification(...)</code>, spec in, query out, which is just a renamed <code>DbSet</code> the moment a derived class wants to start a query from scratch instead of from a spec. <code>ComposeWithRawSql</code> forces the one legitimate use (hand-written SQL, optionally finished off with a spec&rsquo;s includes and ordering) and makes a bare &ldquo;give me the queryable&rdquo; call structurally impossible without actually supplying a SQL fragment. An architecture test pins both its name and its uniqueness down, so a second escape hatch can&rsquo;t quietly show up later without the build noticing.</p>
<p><strong>Inheritance versus composition.</strong> <code>OrderRepository : EfRepository&lt;Order&gt;, IOrderRepository</code> works cleanly for the one aggregate that needs a named method here. The friction is structural rather than syntactic: the base class can only expose one narrow extension point before &ldquo;only one protected member&rdquo; starts eroding, one legitimate exception at a time. A composition-based alternative, a named-method repository that takes <code>IRepository&lt;Order&gt;</code> as a constructor dependency and wraps it instead of inheriting from <code>EfRepository&lt;Order&gt;</code>, would avoid touching the base class&rsquo;s protected surface at all, at the cost of re-implementing <code>Add</code>/<code>Remove</code>/<code>GetByIdAsync</code> as thin delegating calls in every derived repository. I didn&rsquo;t build that second version; for one aggregate it would have been pure ceremony with nothing to show for it. Inheritance earns its keep here specifically because there&rsquo;s exactly one axis of extension and it&rsquo;s unlikely to need a second one across a small number of aggregates. If a third narrow exception ever shows up, that&rsquo;s the signal to switch to composition, not to add a second protected member.</p>
<h2 id="tuning-one-query">Tuning one query</h2>
<p>The generic spec path is correct and consistent, but it isn&rsquo;t free to tune per-query; changing <code>SpecificationEvaluator</code> changes every query that goes through it. The constrained hybrid&rsquo;s actual tuning story is: add exactly one named method, with its own implementation, while every other query keeps using the generic path. <code>IOrderRepository</code> declares the one method this post tunes:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-csharp" data-lang="csharp"><span style="display:flex;"><span><span style="color:#66d9ef">using</span> RepositoryPattern.Domain;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">namespace</span> RepositoryPattern.Application.Abstractions;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">interface</span> <span style="color:#a6e22e">IOrderRepository</span> : IRepository&lt;Order&gt;
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// The one named, tuned query this post defends: it has an EF Core</span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// FromSqlInterpolated implementation, and a behaviorally identical</span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// specification (OpenOrdersForCustomer) that the contract tests pin it to.</span>
</span></span><span style="display:flex;"><span>    Task&lt;List&lt;Order&gt;&gt; GetOpenOrdersForCustomerAsync(Guid customerId, CancellationToken cancellationToken);
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p><code>OpenOrdersForCustomer</code>, shown above, is the method&rsquo;s <em>behavioral definition</em>. <code>OrderRepository</code> implements the method itself with <code>FromSqlInterpolated</code> instead of the LINQ the spec would otherwise generate:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-csharp" data-lang="csharp"><span style="display:flex;"><span><span style="color:#66d9ef">using</span> Microsoft.EntityFrameworkCore;
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">using</span> RepositoryPattern.Application.Abstractions;
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">using</span> RepositoryPattern.Domain;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">namespace</span> RepositoryPattern.Infrastructure.Persistence;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">internal</span> <span style="color:#66d9ef">sealed</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">OrderRepository</span>(OrderingDbContext dbContext) : EfRepository&lt;Order&gt;(dbContext), IOrderRepository
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// The tuned path: hand-written SQL instead of the two-table join EF would</span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// otherwise generate from the spec&#39;s Include(). OpenOrdersForCustomer (the</span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// spec) is this method&#39;s behavioral definition - the contract tests assert</span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// the two return identical rows in identical order.</span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">//</span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// The ORDER BY deliberately lives here, as a LINQ call after Include(),</span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// not inside the raw SQL string above. An ORDER BY written inside a</span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// FromSqlInterpolated string is not preserved once Include() composes a</span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// join on top of it - EF treats the raw SQL as an unordered subquery for</span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// that join, so the embedded ordering is silently dropped from the final</span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// query. This contract test caught exactly that: rows came back in</span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// whatever order the join happened to produce, not the order the SQL</span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// text asked for. ThenBy(order =&gt; order.Id) is still a real tiebreaker on</span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// top of that - the spec path gets one from EF&#39;s own Include() handling,</span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// so this needs to match it for two orders tied on CreatedAt.</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">async</span> Task&lt;List&lt;Order&gt;&gt; GetOpenOrdersForCustomerAsync(Guid customerId, CancellationToken cancellationToken)
</span></span><span style="display:flex;"><span>    {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">var</span> query = ComposeWithRawSql(<span style="color:#e6db74">$&#34;&#34;&#34;
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">            SELECT * FROM orders
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">            WHERE customer_id = {customerId} AND status IN (0, 1)
</span></span></span><span style="display:flex;"><span><span style="color:#e6db74">            &#34;&#34;&#34;</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">await</span> query.Include(order =&gt; order.Lines)
</span></span><span style="display:flex;"><span>            .OrderByDescending(order =&gt; order.CreatedAt).ThenBy(order =&gt; order.Id)
</span></span><span style="display:flex;"><span>            .ToListAsync(cancellationToken);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>A tuned method and its spec can drift apart silently if nothing checks them against each other, so a contract test runs both against the same seeded data and asserts identical rows in identical order:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-csharp" data-lang="csharp"><span style="display:flex;"><span><span style="color:#a6e22e">    [Fact]</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">async</span> Task Spec_path_and_named_method_path_return_identical_orders_in_identical_order()
</span></span><span style="display:flex;"><span>    {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">using</span> var scope = fixture.Services.CreateScope();
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">var</span> orderRepository = scope.ServiceProvider.GetRequiredService&lt;IOrderRepository&gt;();
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">var</span> unitOfWork = scope.ServiceProvider.GetRequiredService&lt;IUnitOfWork&gt;();
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">var</span> customerId = Guid.NewGuid();
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// A short delay between inserts, purely so these two orders have</span>
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// genuinely different CreatedAt values for a meaningful &#34;newest</span>
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// first&#34; check. Correctness here no longer depends on it: both</span>
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// paths now order by CreatedAt descending then Id as a real LINQ</span>
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// call (see OrderRepository.GetOpenOrdersForCustomerAsync), so even</span>
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// a tied CreatedAt would still agree on order.</span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">var</span> draft = Order.Create(customerId);
</span></span><span style="display:flex;"><span>        draft.AddLine(<span style="color:#e6db74">&#34;Widget&#34;</span>, <span style="color:#ae81ff">1</span>, <span style="color:#ae81ff">9.99</span>m);
</span></span><span style="display:flex;"><span>        orderRepository.Add(draft);
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">await</span> Task.Delay(<span style="color:#ae81ff">5</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">var</span> submitted = Order.Create(customerId);
</span></span><span style="display:flex;"><span>        submitted.AddLine(<span style="color:#e6db74">&#34;Gadget&#34;</span>, <span style="color:#ae81ff">2</span>, <span style="color:#ae81ff">4.50</span>m);
</span></span><span style="display:flex;"><span>        submitted.Submit();
</span></span><span style="display:flex;"><span>        orderRepository.Add(submitted);
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">await</span> Task.Delay(<span style="color:#ae81ff">5</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">var</span> shipped = Order.Create(customerId);
</span></span><span style="display:flex;"><span>        shipped.AddLine(<span style="color:#e6db74">&#34;Gizmo&#34;</span>, <span style="color:#ae81ff">1</span>, <span style="color:#ae81ff">19.99</span>m);
</span></span><span style="display:flex;"><span>        shipped.Submit();
</span></span><span style="display:flex;"><span>        shipped.Ship();
</span></span><span style="display:flex;"><span>        orderRepository.Add(shipped);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">var</span> otherCustomersOrder = Order.Create(Guid.NewGuid());
</span></span><span style="display:flex;"><span>        otherCustomersOrder.AddLine(<span style="color:#e6db74">&#34;Widget&#34;</span>, <span style="color:#ae81ff">1</span>, <span style="color:#ae81ff">9.99</span>m);
</span></span><span style="display:flex;"><span>        orderRepository.Add(otherCustomersOrder);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">await</span> unitOfWork.SaveChangesAsync(CancellationToken.None);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">var</span> viaSpec = <span style="color:#66d9ef">await</span> orderRepository.ListAsync(<span style="color:#66d9ef">new</span> OpenOrdersForCustomer(customerId), CancellationToken.None);
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">var</span> viaNamedMethod = <span style="color:#66d9ef">await</span> orderRepository.GetOpenOrdersForCustomerAsync(customerId, CancellationToken.None);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        Assert.Equal(viaSpec.Select(order =&gt; order.Id), viaNamedMethod.Select(order =&gt; order.Id));
</span></span><span style="display:flex;"><span>        Assert.Equal(<span style="color:#ae81ff">2</span>, viaSpec.Count);
</span></span><span style="display:flex;"><span>        Assert.All(viaSpec, order =&gt; Assert.True(order.IsOpen));
</span></span><span style="display:flex;"><span>    }
</span></span></code></pre></div><p>This test failed on me, intermittently, with the exact symptom you&rsquo;d expect from a tie: the two orders coming back in reversed order between the spec path and the tuned path. The obvious theory was that <code>OpenOrdersForCustomer</code> only orders by <code>CreatedAt</code> and says nothing about what should happen when two rows tie on it.</p>
<p>The theory didn&rsquo;t survive contact with a diagnostic. I wrote a throwaway console app that prints full-precision timestamps for both orders and both query results, and the two <code>CreatedAt</code> values weren&rsquo;t close, let alone tied: 400 milliseconds apart, no ambiguity about which came first. The tuned path still returned them in the wrong order anyway. The real bug was in <code>GetOpenOrdersForCustomerAsync</code> itself: its original version wrote <code>ORDER BY created_at DESC</code> <em>inside</em> the <code>FromSqlInterpolated</code> string, then chained <code>.Include(order =&gt; order.Lines)</code> onto the result, and that ordering doesn&rsquo;t survive. EF composes the raw SQL as an unordered subquery to perform the join <code>Include()</code> needs, so whatever order the SQL text asks for is advisory at best once a collection include is layered on top of it.</p>
<p>The fix is already in the code above: the <code>ORDER BY</code> moved out of the SQL string entirely and became a real LINQ call after <code>.Include()</code>, <code>.OrderByDescending(order =&gt; order.CreatedAt).ThenBy(order =&gt; order.Id)</code>, which guarantees EF adds the ordering to the outermost composed query instead of a subquery that&rsquo;s free to be reordered. The <code>ThenBy(order =&gt; order.Id)</code> earns its place too: the spec path still gets an implicit secondary sort on the primary key from EF&rsquo;s own <code>Include()</code> handling, so the tuned path needs the same tiebreaker to agree with it on the days <code>CreatedAt</code> really does tie. This is a sharper cost than I expected going in. An <code>ORDER BY</code> written inside hand-written SQL that&rsquo;s later composed with <code>Include()</code> isn&rsquo;t just missing a tiebreaker, it isn&rsquo;t a trustworthy order at all, and the only real fix is to never rely on it there in the first place.</p>
<p><strong>The measured numbers.</strong> Seeding, via a standalone Npgsql binary <code>COPY</code> with no EF Core in the hot path: 50,000 orders and roughly 100,000 order lines in 0.9 seconds, inside the <code>migrate-and-seed</code> container, on this machine. Query timing, for the busiest seeded customer (30 open orders out of 50,000 total orders across 2,000 customers), 50 iterations each, first call discarded as a warm-up, measured from a throwaway console app against the same running Postgres container, not part of the published code:</p>
<table>
  <thead>
      <tr>
          <th>Path</th>
          <th>Avg per call</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td>Spec path (<code>ListAsync(new OpenOrdersForCustomer(id))</code>, EF-translated LINQ + <code>Include</code>)</td>
          <td>2.87 ms</td>
      </tr>
      <tr>
          <td>Tuned path (<code>GetOpenOrdersForCustomerAsync(id)</code>, <code>FromSqlInterpolated</code> + <code>Include</code>)</td>
          <td>1.82 ms</td>
      </tr>
  </tbody>
</table>
<p>About a 37% reduction, on this query, on this data shape, on one machine. Both paths still run the same <code>Include</code>-driven join for <code>Lines</code>; the gap comes from EF&rsquo;s LINQ translation and query-plan overhead on the filter and sort, not from avoiding the join. I don&rsquo;t want to oversell this. It&rsquo;s a modest number for a <code>WHERE</code> plus <code>ORDER BY</code> over an indexed column, and the win from having a named, tunable seam isn&rsquo;t usually going to be dramatic on a query this simple. It should matter more as a query gets more complex than this one (aggregations, window functions, joins EF Core can&rsquo;t express cleanly), which this post doesn&rsquo;t need to demonstrate, because the point of the comparison is the seam existing at all, not this specific number.</p>
<h2 id="enforcing-it">Enforcing it</h2>
<p>A design like this is only as good as what stops someone from quietly reaching back into <code>DbContext</code> the next time a deadline is tight. Two kinds of rule do that here, for two different kinds of violation.</p>
<p><strong>Dependency direction, with ArchUnitNET.</strong> Domain depends on nothing else in the solution; Application and Api don&rsquo;t depend on EF Core; nothing outside Infrastructure depends on Infrastructure&rsquo;s persistence internals:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-csharp" data-lang="csharp"><span style="display:flex;"><span><span style="color:#a6e22e">    [Fact]</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">void</span> Domain_depends_on_nothing_else_in_the_solution()
</span></span><span style="display:flex;"><span>    {
</span></span><span style="display:flex;"><span>        Types().That().ResideInNamespaceOrBelow(<span style="color:#e6db74">&#34;RepositoryPattern.Domain&#34;</span>)
</span></span><span style="display:flex;"><span>            .Should().NotDependOnAny(Types().That().ResideInNamespaceOrBelow(<span style="color:#e6db74">&#34;RepositoryPattern.Application&#34;</span>))
</span></span><span style="display:flex;"><span>            .AndShould().NotDependOnAny(Types().That().ResideInNamespaceOrBelow(<span style="color:#e6db74">&#34;RepositoryPattern.Infrastructure&#34;</span>))
</span></span><span style="display:flex;"><span>            .AndShould().NotDependOnAny(Types().That().ResideInNamespaceOrBelow(<span style="color:#e6db74">&#34;Microsoft.EntityFrameworkCore&#34;</span>))
</span></span><span style="display:flex;"><span>            .Check(Architecture);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">    [Fact]</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">void</span> Application_does_not_depend_on_entity_framework_core()
</span></span><span style="display:flex;"><span>    {
</span></span><span style="display:flex;"><span>        Types().That().ResideInNamespaceOrBelow(<span style="color:#e6db74">&#34;RepositoryPattern.Application&#34;</span>)
</span></span><span style="display:flex;"><span>            .Should().NotDependOnAny(Types().That().ResideInNamespaceOrBelow(<span style="color:#e6db74">&#34;Microsoft.EntityFrameworkCore&#34;</span>))
</span></span><span style="display:flex;"><span>            .Check(Architecture);
</span></span><span style="display:flex;"><span>    }
</span></span></code></pre></div><p><code>Comparisons</code> is deliberately exempt from the EF Core rule, since options 1-4 need to reference it directly to exist at all; that exemption is documented right next to the rule it would otherwise trip. A real app wouldn&rsquo;t need this exemption at all: it ships one implementation, not four kept around for comparison, so nothing outside <code>Infrastructure</code> would ever need direct EF Core access.</p>
<p>The rule that always passed is the lesson worth remembering from this project. The first version of <code>Application_does_not_depend_on_entity_framework_core</code> reported zero violations from the day I wrote it, and I nearly took that as a sign the rule worked. It didn&rsquo;t; <code>Microsoft.EntityFrameworkCore.DbContext</code> wasn&rsquo;t a real node in ArchUnitNET&rsquo;s loaded model yet, just an unresolved external reference nothing could match a namespace selector against. The fix was loading EF Core&rsquo;s own assembly into the architecture explicitly:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-csharp" data-lang="csharp"><span style="display:flex;"><span><span style="color:#66d9ef">internal</span> <span style="color:#66d9ef">static</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">Architectures</span>
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// Loaded once and shared by every rule below. Api is a top-level-statement</span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// minimal API with no public type of its own to anchor a `typeof`, so it&#39;s</span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// loaded by assembly name instead.</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">static</span> <span style="color:#66d9ef">readonly</span> Architecture Full = <span style="color:#66d9ef">new</span> ArchLoader()
</span></span><span style="display:flex;"><span>        .LoadAssemblies(
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">typeof</span>(RepositoryPattern.Domain.IAggregateRoot).Assembly,
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">typeof</span>(RepositoryPattern.Application.Abstractions.IRepository&lt;&gt;).Assembly,
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">typeof</span>(RepositoryPattern.Infrastructure.ServiceCollectionExtensions).Assembly,
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">typeof</span>(RepositoryPattern.Comparisons.Shared.ComparisonDbContext).Assembly,
</span></span><span style="display:flex;"><span>            Assembly.Load(<span style="color:#e6db74">&#34;RepositoryPattern.Api&#34;</span>),
</span></span><span style="display:flex;"><span>            <span style="color:#75715e">// Loaded explicitly so EF Core&#39;s own types are full members of the</span>
</span></span><span style="display:flex;"><span>            <span style="color:#75715e">// model - otherwise a &#34;depends on Microsoft.EntityFrameworkCore&#34;</span>
</span></span><span style="display:flex;"><span>            <span style="color:#75715e">// rule has nothing concrete to match against.</span>
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">typeof</span>(Microsoft.EntityFrameworkCore.DbContext).Assembly)
</span></span><span style="display:flex;"><span>        .Build();
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>I only caught it because the plan called for a deliberate negative check: temporarily make the Api project call <code>OrderingDbContext</code> directly, confirm the rule actually fails, then revert. Running that check is what surfaced the assembly-loading gap; without it, the rule would have shipped green for the wrong reason, which is worse than not having the rule at all, since a rule that always passes still <em>looks</em> like protection.</p>
<p><strong>Structural rules, with plain reflection.</strong> Generic-parameter constraints, access modifiers, and &ldquo;exactly one protected member of this shape&rdquo; aren&rsquo;t naturally dependency-direction questions, so they&rsquo;re checked with reflection instead of forcing ArchUnitNET to do a job it isn&rsquo;t built for:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-csharp" data-lang="csharp"><span style="display:flex;"><span><span style="color:#a6e22e">    [Fact]</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">void</span> EfRepository_exposes_no_DbSet_or_DbContext_as_a_protected_member_and_only_one_IQueryable_returning_helper()
</span></span><span style="display:flex;"><span>    {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">var</span> infrastructureAssembly = <span style="color:#66d9ef">typeof</span>(ServiceCollectionExtensions).Assembly;
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">var</span> efRepositoryType = infrastructureAssembly.GetType(<span style="color:#e6db74">&#34;RepositoryPattern.Infrastructure.Persistence.EfRepository`1&#34;</span>)
</span></span><span style="display:flex;"><span>            ?? <span style="color:#66d9ef">throw</span> <span style="color:#66d9ef">new</span> InvalidOperationException(<span style="color:#e6db74">&#34;EfRepository&lt;T&gt; was not found - did it get renamed or moved?&#34;</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">var</span> protectedMembers = efRepositoryType
</span></span><span style="display:flex;"><span>            .GetMethods(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)
</span></span><span style="display:flex;"><span>            .Where(method =&gt; method.IsFamily)
</span></span><span style="display:flex;"><span>            .ToList();
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        Assert.All(protectedMembers, member =&gt;
</span></span><span style="display:flex;"><span>        {
</span></span><span style="display:flex;"><span>            Assert.DoesNotContain(<span style="color:#e6db74">&#34;DbSet&#34;</span>, member.ReturnType.Name);
</span></span><span style="display:flex;"><span>            Assert.DoesNotContain(<span style="color:#e6db74">&#34;DbContext&#34;</span>, member.ReturnType.Name);
</span></span><span style="display:flex;"><span>        });
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">var</span> queryReturningMembers = protectedMembers.Where(member =&gt; member.ReturnType.Name.Contains(<span style="color:#e6db74">&#34;IQueryable&#34;</span>)).ToList();
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// The one narrow exception this post allows: ComposeWithRawSql, which</span>
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// composes a hand-written SQL fragment with an optional spec and</span>
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// returns a query, for a derived named-method repository to finish</span>
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// with Include()/ToListAsync(). Nothing else protected is allowed to</span>
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// hand back a query.</span>
</span></span><span style="display:flex;"><span>        Assert.Single(queryReturningMembers);
</span></span><span style="display:flex;"><span>        Assert.Equal(<span style="color:#e6db74">&#34;ComposeWithRawSql&#34;</span>, queryReturningMembers[<span style="color:#ae81ff">0</span>].Name);
</span></span><span style="display:flex;"><span>    }
</span></span></code></pre></div><p>The generic constraint itself (<code>where T : class, IAggregateRoot</code>) is already enforced at compile time; the reflection test against it is really a regression guard against someone <em>removing</em> the constraint later, not a runtime check catching something the compiler would have missed.</p>
<p>Two short notes worth knowing before you copy either tool into your own project: running integration tests and comparison tests in parallel against the same real Postgres database is a trap, since parallel test collections each truncating shared tables mid-test is a real, reproducible flaky failure, not a hypothetical one; <code>[assembly: CollectionBehavior(DisableTestParallelization = true)]</code> fixed it here. And a minimal API&rsquo;s top-level-statement <code>Program.cs</code> leaves no public type in its own namespace to anchor a <code>typeof()</code> against, so Api had to be selected by assembly name instead, and even then, an exact assembly-name match failed because ArchUnitNET compares against the full assembly name (version, culture, token included), not the simple one; a pattern match was the fix.</p>
<h2 id="where-this-loses-and-when-to-skip-it">Where this loses, and when to skip it</h2>
<p>The <code>ScenarioEquivalenceTests</code> in the companion code prove all five options are behaviorally identical for this one scenario. Nobody on the list above is actually wrong about correctness. The differences are all about longer-term properties: testability without a database, a compiler-enforced aggregate boundary, a named seam for tuning one query. Those properties don&rsquo;t come as a single package, though, so which of the three constrained shapes is worth building depends on which ones you actually need enforced.</p>
<p>One constraint is worth keeping no matter which of these you build: <code>IAggregateRoot</code>. It&rsquo;s a marker interface and a generic constraint, nothing more. For a generic repository (options 4 and 5), it lives directly on the interface&rsquo;s own type parameter. For a non-generic shape (a query object or a classic repository, options 2 and 3), the interface has no type parameter to constrain, but the implementation can still derive from a thin, otherwise-empty base class, <code>AggregateQueryObject&lt;TAggregate&gt;</code> or <code>AggregateRepository&lt;TAggregate&gt;</code>, that exists only to carry it. Either way, it&rsquo;s what stops a query object or a repository method from quietly being written against <code>OrderLine</code> instead of <code>Order</code>, reaching past the aggregate root the same way a bare <code>DbSet&lt;OrderLine&gt;</code> would. Only option 1, with no class or interface of its own to attach anything to, can&rsquo;t have it. Every other shape in this list can, and should.</p>
<p><strong>Skip the seam entirely when:</strong></p>
<ul>
<li>You have one aggregate, a handful of queries, and no reason to think that changes. Option 1 is 24 lines and nothing else.</li>
<li>Nobody on the team is asking for unit tests that run without a database. If integration tests against a real, fast-to-spin-up database are an accepted cost already, specification-level testability doesn&rsquo;t move the needle.</li>
</ul>
<p>Query objects (option 2) and a classic named-method repository (option 3) sit in between, and they&rsquo;re legitimate stopping points of their own, not just steps toward something better. A query object gets you a named, swappable seam without <code>ISpecification&lt;T&gt;</code> at all. Reach for it when you want queries extracted into their own classes, one per use case, but don&rsquo;t care about testing the query logic without a database. A classic repository adds an interface worth mocking at the handler level, plus a thin <code>AggregateRepository&lt;TAggregate&gt;</code> base to carry the <code>IAggregateRoot</code> constraint, without the specification machinery. Reach for it when you want that governance and that kind of handler-level test, but each query is simple enough that hand-writing its one method is less ceremony than building a spec for it.</p>
<p><strong>A plain specification repository (option 4) is probably enough when:</strong></p>
<ul>
<li>You&rsquo;re fine without every new aggregate automatically getting a working repository implementation. Because <code>EfRepository&lt;T&gt;</code> is registered once as an open generic, any type that implements <code>IAggregateRoot</code> gets a complete, working <code>IRepository&lt;T&gt;</code> the instant it&rsquo;s declared, no new class, no extra registration. A plain specification repository, built without that open-generic registration, doesn&rsquo;t give you that: each aggregate still needs its own small class wiring up the interface, even though it leans on the same <code>ISpecification&lt;T&gt;</code> and evaluator underneath.</li>
<li>You don&rsquo;t yet need a dedicated tuning seam. Tuning one query is still possible (swap the generic evaluator for everyone, or bypass the abstraction for that one case); it&rsquo;s just not as clean as a named method, an acceptable tradeoff if you don&rsquo;t expect to need it often.</li>
</ul>
<p><strong>Reach for the full constrained hybrid (option 5) when:</strong></p>
<ul>
<li>You want the dependency-direction rules (no EF Core above Infrastructure, nothing outside Infrastructure touching its internals) and the aggregate-root boundary enforced by a failing build, not a PR comment someone might not leave.</li>
<li>A second aggregate is coming, and you can already tell some of its queries will need the same kind of tuning this post gave <code>GetOpenOrdersForCustomerAsync</code>: a named method with its own implementation, without disturbing the generic path everything else still uses.</li>
<li>The team is big enough, or turns over enough, that &ldquo;we don&rsquo;t do that here&rdquo; needs to be something the compiler and the test suite say, not something a tribal-knowledge reviewer remembers to catch.</li>
</ul>
<p>The moment an aggregate needs even one named method, it needs its own interface, its own <code>internal</code> class deriving from <code>EfRepository&lt;T&gt;</code>, and a DI registration line. That&rsquo;s real, per-aggregate ceremony, and most systems that live long enough end up with more than one aggregate with special needs. Whether that ceremony is worth paying for, and whether the <code>IAggregateRoot</code> boundary on top of it is worth paying for too, depends entirely on which of these properties you actually expect to need, not on how the five code samples compare side by side for the one query this post explored.</p>
]]></content:encoded></item></channel></rss>