Skip to content

Data Access

Rule prefix: DATA · Baseline: C# 14 / .NET 10 · Levels: DO · DO NOT · CONSIDER · AVOID

Home · Rule index · Naming cheat sheet

This chapter covers the style conventions that are specific to EF Core, Dapper and ADO.NET: names for contexts, entities, sets, keys, migrations and query methods, usage rules for asynchronous calls with a cancellation token and parameterized raw SQL, and rules for the shape of a query (tracking, related data, filtering in the database, limits and projection). It does not cover schema design, relationships, inheritance mapping, indexes, database-side naming or repository architecture. Dependency-injection lifetimes, including the lifetime of a DbContext, are covered on page 16.

General rules are linked, not repeated. Casing and prefixes are in the naming pages (NAM-110 for types, NAM-130 for methods), the Async suffix (NAM-131) and token forwarding in page 11, and the reasons behind parameterized SQL in page 13. C# names always follow C# conventions: a database column called order_id is mapped in configuration, and the C# property is still OrderId.

Rule index

ID Level Rule Enforced
DATA-001 DO name a DbContext subclass <Domain>DbContext (OrderingDbContext), never Context, DataContext, AppDbContext or MyDbContext. Manual
DATA-002 DO name an entity class with a singular PascalCase noun (Order, OrderLine) without tbl, Entity, Model or Dto prefixes or suffixes. IDE1006
DATA-003 DO name each DbSet<T> property with the plural of its entity and declare it as an expression-bodied call to Set<T>() (public DbSet<Order> Orders => Set<Order>();). Manual
DATA-004 DO name a primary key Id, a foreign key <Entity>Id (CustomerId) and the navigation property after the foreign key without Id (Customer), never ID, Key, Fk_ or underscores. CA1707
DATA-006 DO give a migration a descriptive imperative PascalCase name (AddShipmentTrackingNumber), never Migration1, Update or Fix, and never hand-format or rename generated migration files afterwards. Manual
DATA-007 DO call the asynchronous EF Core and ADO.NET APIs (ToListAsync, FirstOrDefaultAsync, SaveChangesAsync, ExecuteReaderAsync) in async code and pass the method's CancellationToken to each of them. CA1849, CA2016
DATA-010 DO build raw SQL only with EF Core FromSql or ExecuteSql (whose interpolation holes become parameters) or with a constant SQL string plus a Dapper parameter object, and never call FromSqlRaw, ExecuteSqlRaw or Dapper with SQL built by concatenation or interpolation. EF1002, EF1003
DATA-012 DO name a query method after what it returns: Get…Async when the result must exist (throws otherwise), Find…Async when it may return null, List…Async for collections, Exists…Async for bool and Count…Async for counts. Manual
DATA-020 DO add AsNoTracking() to every EF Core query whose entities are only read and never saved. Manual
DATA-021 DO NOT query related rows once per parent row (the N+1 pattern); load them in the same query with Include or a Select projection. Manual
DATA-022 DO NOT call ToList, ToArray, ToListAsync or AsEnumerable before a Where, OrderBy, Skip, Take or aggregate that the database can run; put those operators first and materialize last. Manual
DATA-023 DO bound every query that returns a list, with Take after a unique OrderBy (Skip and Take for numbered pages) or with a keyset Where on the sort key (Id > lastId) for deep pages. Manual
DATA-024 CONSIDER project a read-only result into a small type with Select instead of loading whole entities. Manual

Data-access naming

These rules name contexts, entities, sets, keys, migrations and query methods.

DATA-001

DO name a DbContext subclass <Domain>DbContext (OrderingDbContext), never Context, DataContext, AppDbContext or MyDbContext.

✅ Correct

using Microsoft.EntityFrameworkCore;

namespace Contoso.Orders;

public sealed class OrderingDbContext(DbContextOptions<OrderingDbContext> options) : DbContext(options)
{
    public DbSet<Order> Orders => Set<Order>();
}

❌ Incorrect — the name says nothing about the domain

using Microsoft.EntityFrameworkCore;

namespace Contoso.Orders;

public sealed class MyDbContext(DbContextOptions<MyDbContext> options) : DbContext(options) // no domain in the name
{
    public DbSet<Order> Orders => Set<Order>();
}

Why: The domain name tells a reader which part of the model the context owns. A solution with a second context then needs no renaming, and commands such as dotnet ef migrations add AddShipmentTrackingNumber --context OrderingDbContext read correctly. Context, DataContext, AppDbContext and MyDbContext describe the technology or the author, not the data. IDE1006 can check capitalization, prefix and suffix but not word choice, so this is a manual rule that reviewers check (TOOL-018).

Scope: EF Core DbContext classes · Enforced: Manual · Sources: MS-FDG-TYPES, AV

DATA-002

DO name an entity class with a singular PascalCase noun (Order, OrderLine) without tbl, Entity, Model or Dto prefixes or suffixes.

✅ Correct

namespace Contoso.Orders;

public sealed class Shipment
{
    public int Id { get; set; }

    public int OrderId { get; set; }
}

❌ Incorrect — tbl prefix in lower case and an Entity suffix

namespace Contoso.Orders;

public sealed class tblShipment // lower-case first letter
{
    public int Id { get; set; }
}

public sealed class ShipmentEntity // Entity suffix
{
    public int Id { get; set; }
}

Why: An entity represents one row, so its name is the singular noun of the thing (Shipment). A tbl prefix is Hungarian notation (NAM-205). A suffix such as ShipmentEntity or ShipmentModel repeats what the type's place in the code already says and makes every query read longer. IDE1006 reports the lower-case first letter of tblShipment; it cannot tell that ShipmentEntity carries an unwanted suffix, so reviewers check affixes. Casing follows NAM-110.

Exceptions: A type that is not an entity (a request or response contract) may end in Dto when that tells it apart from the entity of the same name.

Scope: Entity classes mapped by EF Core or Dapper · Enforced: IDE1006 · Config: dotnet_naming_rule.nam_110_types.*, resharper_csharp_naming_rule.types_and_namespaces · Sources: MS-FDG-TYPES, MS-IDE-NAMING, AV

DATA-003

DO name each DbSet<T> property with the plural of its entity and declare it as an expression-bodied call to Set<T>() (public DbSet<Order> Orders => Set<Order>();).

✅ Correct

using Microsoft.EntityFrameworkCore;

namespace Contoso.Orders;

public sealed class OrderingDbContext(DbContextOptions<OrderingDbContext> options) : DbContext(options)
{
    public DbSet<Order> Orders => Set<Order>();
}

❌ Incorrect — singular name and public setter

using Microsoft.EntityFrameworkCore;

namespace Contoso.Orders;

public sealed class OrderingDbContext(DbContextOptions<OrderingDbContext> options) : DbContext(options)
{
    public DbSet<Order> Order { get; set; } // singular name for a collection

    public DbSet<OrderLine> OrderLines { get; set; } // public setter lets callers replace the set
}

Why: A DbSet<T> is a collection of entities, so its name is plural. The expression-bodied form has no setter, so callers cannot replace the set, and it states that the context owns it. It also does not depend on the CS8618 suppressor that EF Core 7 and later ship for settable DbSet<T> properties, which already makes { get; set; } free of that warning. No analyzer checks the declaration style or the plural, so this is a manual rule.

Scope: DbSet properties of a DbContext · Enforced: Manual · Sources: MS-FDG-MEMBERS, MS-NRT

DATA-004

DO name a primary key Id, a foreign key <Entity>Id (CustomerId) and the navigation property after the foreign key without Id (Customer), never ID, Key, Fk_ or underscores.

✅ Correct

namespace Contoso.Orders;

public sealed class Shipment
{
    public int Id { get; set; }

    public int OrderId { get; set; }

    public Order? Order { get; set; }
}

❌ Incorrect — underscore in a foreign key

namespace Contoso.Orders;

public sealed class Shipment
{
    public int Id { get; set; }

    public int Order_Id { get; set; } // underscore in a foreign key

    public Order? Order { get; set; }
}

Why: Id is an abbreviation, not an acronym, so it is written Id and never ID (NAM-012). The navigation property carries the foreign-key stem (Order for OrderId), which makes the pair obvious at every use. Names such as ID, Key or FkOrder hide that pair, and underscores break the C# naming rules (CA1707).

Scope: Key, foreign-key and navigation properties of entities · Enforced: CA1707 · Sources: MS-FDG-CAPS, MS-CA

DATA-006

DO give a migration a descriptive imperative PascalCase name (AddShipmentTrackingNumber), never Migration1, Update or Fix, and never hand-format or rename generated migration files afterwards.

✅ Correct

dotnet ef migrations add AddShipmentTrackingNumber

❌ Incorrect — meaningless, numbered name

dotnet ef migrations add Update2 # meaningless, numbered name

Why: The migration name is stored in the __EFMigrationsHistory table and shown by dotnet ef migrations list, so it is read for as long as the database exists. An imperative name states the change (AddShipmentTrackingNumber, RenameOrderStatusColumn), where Update2 states nothing. The tool rewrites the model snapshot on every migrations add, so hand formatting creates noise in later diffs, and renaming a migration that is already applied breaks its link to the history table. To rename a migration that is not yet applied, run dotnet ef migrations remove and add it again. No diagnostic checks migration names, so this is a manual rule.

The shipped .editorconfig sets generated_code = true for files inside a Migrations folder, at any depth, whose names contain an underscore, end in .Designer.cs or end in ModelSnapshot.cs. That matches the files EF Core generates, so the first dotnet ef migrations add builds without warnings while warnings fail the build. The cost is that analyzers do not run on those files at all, security rules included. The setting matches names, not authorship: a hand-written file in a Migrations folder that has an underscore in its name (Seed_Data.cs) or ends in .Designer.cs is silenced too, while a hand-written MigrationHelpers.cs is still analyzed. Hand-written migration files named <timestamp>_<name>, as FluentMigrator and DbUp use, are treated as generated too, and the folder name is matched with its exact case (Migrations, not migrations). Three habits follow. Keep hand-written code out of Migrations folders, and when a hand-written file must be there, give it a name without an underscore and without the .Designer.cs and ModelSnapshot.cs endings. Do not hand-edit generated files to silence a warning. Review raw SQL in a migration by hand, for example a migrationBuilder.Sql(...) call, because no analyzer inspects it (DATA-010, SEC-030).

Exceptions: The first migration of a new database may be called InitialCreate, the name the EF Core documentation uses.

Scope: EF Core migrations · Enforced: Manual · Config: generated_code · Sources: MS-EF, AV

Data-access usage

These rules cover asynchronous calls with a cancellation token and parameterized raw SQL.

DATA-007

DO call the asynchronous EF Core and ADO.NET APIs (ToListAsync, FirstOrDefaultAsync, SaveChangesAsync, ExecuteReaderAsync) in async code and pass the method's CancellationToken to each of them.

✅ Correct

public static Task<Order?> FindOrderAsync(DbContext context, int orderId, CancellationToken cancellationToken = default)
{
    return context.Set<Order>().FirstOrDefaultAsync(order => order.Id == orderId, cancellationToken);
}

public static async Task<int> AddAndSaveAsync(DbContext context, Order order,
    CancellationToken cancellationToken = default)
{
    await context.AddAsync(order, cancellationToken);

    return await context.SaveChangesAsync(cancellationToken);
}

❌ Incorrect — synchronous call and a token that is not forwarded

public static async Task<int> AddAndSaveAsync(DbContext context, Order order,
    CancellationToken cancellationToken = default)
{
    await context.AddAsync(order, cancellationToken);

    return context.SaveChanges(); // synchronous call inside an async method
}

public static async Task<int> CountOrdersAsync(DbContext context, CancellationToken cancellationToken = default)
{
    return await context.Set<Order>().CountAsync(); // cancellationToken is not forwarded
}

Why: A synchronous database call holds a thread while the database works, which limits how many requests the process can serve (ASYNC-010). The token lets the database call stop when the caller gives up, for example when a client closes the connection. Diagnostic CA1849 reports a synchronous call inside an async method when an async version exists, and CA2016 reports a token that is in scope but not passed. Every EF Core async method and DbCommand.ExecuteReaderAsync accept a CancellationToken, so pass it every time (ASYNC-012). A method that only forwards the call, like FindOrderAsync, returns the task without async and await; a method that does more after the first call, like AddAndSaveAsync, awaits (ASYNC-015).

See also: ASYNC-010 (await all the way up), ASYNC-012 (token as the last parameter).

Scope: Data access in asynchronous code paths · Enforced: CA1849, CA2016 · Sources: MS-CA, MS-EF, MS-TAP

DATA-010

DO build raw SQL only with EF Core FromSql or ExecuteSql (whose interpolation holes become parameters) or with a constant SQL string plus a Dapper parameter object, and never call FromSqlRaw, ExecuteSqlRaw or Dapper with SQL built by concatenation or interpolation.

✅ Correct

public static int DeleteOrder(DbContext context, int orderId)
{
    return context.Database.ExecuteSql($"DELETE FROM Orders WHERE Id = {orderId}");
}

✅ Correct — Dapper with a constant SQL string and a parameter object

private const string FindSql = "SELECT Id, Name FROM Customers WHERE Id = @CustomerId";

public static async Task<Customer?> FindAsync(IDbConnection connection, int id,
    CancellationToken cancellationToken = default)
{
    var query = new CommandDefinition(FindSql, new { CustomerId = id }, cancellationToken: cancellationToken);

    return await connection.QuerySingleOrDefaultAsync<Customer>(query);
}

❌ Incorrect — interpolated string into raw SQL — Insecure, do not use

// INSECURE: an interpolated string is built first and then sent as raw SQL, so the value becomes SQL text
public static int DeleteOrder(DbContext context, int orderId)
{
    return context.Database.ExecuteSqlRaw($"DELETE FROM Orders WHERE Id = {orderId}"); // interpolated string into raw SQL
}

❌ Incorrect — value concatenated into Dapper SQL — Insecure, do not use

// INSECURE: the name is concatenated into the SQL text that Dapper sends
public static Task<IEnumerable<Customer>> ListByNameAsync(IDbConnection connection, string name)
{
    string sql = "SELECT Id, Name FROM Customers WHERE Name = '" + name + "'"; // value concatenated into SQL

    return connection.QueryAsync<Customer>(sql);
}

Why: ExecuteSql($"...") looks like string interpolation, but the argument type is FormattableString. The compiler passes the format text and the values to EF Core separately, and EF Core sends each hole as a database parameter. ExecuteSqlRaw takes a string, so the interpolation runs before EF Core sees it and the value is already part of the SQL text. A string you built earlier loses the parameters in the same way, and FromSql does not accept a plain string variable for that reason. With Dapper, keep the SQL constant and put values in the parameter object. Table and column names cannot be parameters, so take them from an allow-list (SEC-030). Diagnostics EF1002 and EF1003 inspect only the argument written inline in the call to a Raw method; a SQL string built in a variable first is not reported, so reviewers check every Raw call whose argument is a variable.

See also: SEC-030 (parameterized SQL in ADO.NET, with the security reasoning).

Scope: Raw SQL in EF Core and Dapper · Enforced: EF1002, EF1003 · Sources: MS-EF, MS-EFA, DAPPER, OWASP-SQLI

DATA-012

DO name a query method after what it returns: Get…Async when the result must exist (throws otherwise), Find…Async when it may return null, List…Async for collections, Exists…Async for bool and Count…Async for counts.

✅ Correct

namespace Contoso.Orders;

public interface IOrderQueries
{
    Task<Order> GetAsync(int orderId, CancellationToken cancellationToken = default);

    Task<Order?> FindAsync(int orderId, CancellationToken cancellationToken = default);

    Task<IReadOnlyList<Order>> ListByCustomerAsync(int customerId, CancellationToken cancellationToken = default);

    Task<bool> ExistsAsync(int orderId, CancellationToken cancellationToken = default);

    Task<int> CountPendingAsync(CancellationToken cancellationToken = default);
}

❌ Incorrect — names that promise a different result

namespace Contoso.Orders;

public interface IOrderQueries
{
    Task<Order?> GetAsync(int orderId, CancellationToken cancellationToken = default); // Get that may return null

    Task<IReadOnlyList<Order>> GetOrdersAsync(int customerId, CancellationToken cancellationToken = default); // A list
}

Why: The verb tells the caller how to handle the result without opening the method. After GetAsync the caller can use the value, because a missing row throws (for example OrderNotFoundException). After FindAsync the caller must check for null. List… signals a collection that may be empty, Exists… a bool, and Count… a number. A Get that returns null breaks that contract and produces null-reference errors far from the query. This chapter defines the query-name vocabulary, and the general method-name rule is NAM-130. The Async suffix follows NAM-131 and the token parameter ASYNC-012. No diagnostic can check word choice, so this is a manual rule.

Exceptions: A method that changes state (PlaceOrderAsync) is a command, not a query, and is named by NAM-130.

See also: NAM-130 (method names).

Scope: Names of query methods, in any class · Enforced: Manual · Sources: MS-FDG-MEMBERS, MS-TAP

Query shape and efficiency

These rules cover how a query reads data: whether EF Core tracks the result, how related rows are loaded, which work the database does, how many rows come back and which columns are read. No analyzer checks them, so reviewers do (TOOL-018). The examples use EF Core with an Order that has a CustomerId, a PlacedAt of type DateTimeOffset (VAR-040) and a collection of OrderLine rows with a Quantity and a UnitPrice; the same ideas apply to a Dapper query as far as they fit.

DATA-020

DO add AsNoTracking() to every EF Core query whose entities are only read and never saved.

✅ Correct

public static Task<Order?> FindForDisplayAsync(DbContext context, int orderId,
    CancellationToken cancellationToken = default)
{
    return context.Set<Order>()
        .AsNoTracking()
        .FirstOrDefaultAsync(order => order.Id == orderId, cancellationToken);
}

❌ Incorrect — a tracking query for a result that is only displayed

public static Task<Order?> FindForDisplayAsync(DbContext context, int orderId,
    CancellationToken cancellationToken = default)
{
    return context.Set<Order>()
        .FirstOrDefaultAsync(order => order.Id == orderId, cancellationToken); // tracked, but never saved
}

Why: A query that returns entities is a tracking query by default. EF Core registers each entity in the change tracker and keeps a snapshot of it, so that SaveChanges can find what changed. Code that only reads the result never saves it, so tracking costs time and memory for nothing; the EF Core documentation says to use a no-tracking query for read-only results. A no-tracking query does not look for entities it has already loaded, so a row that several results refer to is created once per reference. Use AsNoTrackingWithIdentityResolution() when that duplication matters. No analyzer knows whether the result is saved later, so this is a manual rule.

Exceptions:

  • A query whose entities the code changes and saves in the same unit of work stays a tracking query.
  • A context configured with UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking) needs no AsNoTracking() call; add AsTracking() to the queries that save.
  • A query that projects into a type that is not an entity (DATA-024) is never tracked.

Scope: EF Core queries that return entities · Enforced: Manual · Sources: MS-EF-TRACKING, MS-EF-PERF

DATA-021

DO NOT query related rows once per parent row (the N+1 pattern); load them in the same query with Include or a Select projection.

✅ Correct

public static async Task<IReadOnlyList<Order>> ListWithLinesAsync(DbContext context, int customerId,
    CancellationToken cancellationToken = default)
{
    return await context.Set<Order>()
        .AsNoTracking()
        .Include(order => order.Lines)
        .Where(order => order.CustomerId == customerId)
        .OrderBy(order => order.Id)
        .Take(100)
        .ToListAsync(cancellationToken);
}

❌ Incorrect — one extra query for every order

public static async Task<IReadOnlyList<Order>> ListWithLinesAsync(DbContext context, int customerId,
    CancellationToken cancellationToken = default)
{
    List<Order> orders = await context.Set<Order>()
        .AsNoTracking()
        .Where(order => order.CustomerId == customerId)
        .OrderBy(order => order.Id)
        .Take(100)
        .ToListAsync(cancellationToken);

    foreach (Order order in orders)
    {
        List<OrderLine> lines = await context.Set<OrderLine>()
            .AsNoTracking()
            .Where(line => line.OrderId == order.Id)
            .ToListAsync(cancellationToken); // one query per order

        foreach (OrderLine line in lines)
        {
            order.Lines.Add(line);
        }
    }

    return orders;
}

Why: The first query returns the parents, and each pass through the loop sends another query for one parent's children: 1 query plus N, hence the name. Every query is a round trip to the database, so the cost grows with the number of parents and shows up only when the data is real. Include loads the children in the same query, and a Select projection (DATA-024) reads only the columns you need from both sides. Lazy loading hides the same pattern, because each access to a navigation property sends a query; the EF Core documentation recommends avoiding it, because eager and explicit loading show in the source where a round trip happens. When a query loads several collections at once, the joins can repeat the parent data many times; the EF Core documentation describes split queries for that case. No analyzer detects the loop, so this is a manual rule.

Exceptions:

  • Load related rows separately when you only know after the first query whether you need them, for example after a call to another service. Then load them for all parents at once, not one parent at a time.

Scope: Code that loads child rows for a list of parents · Enforced: Manual · Sources: MS-EF-PERF, MS-EF-RELATED

DATA-022

DO NOT call ToList, ToArray, ToListAsync or AsEnumerable before a Where, OrderBy, Skip, Take or aggregate that the database can run; put those operators first and materialize last.

✅ Correct

public static async Task<IReadOnlyList<Order>> ListLatestAsync(DbContext context, int customerId,
    CancellationToken cancellationToken = default)
{
    return await context.Set<Order>()
        .AsNoTracking()
        .Where(order => order.CustomerId == customerId)
        .OrderByDescending(order => order.PlacedAt)
        .Take(50)
        .ToListAsync(cancellationToken); // Filter, sort and limit run in the database
}

❌ Incorrect — every order is loaded and then filtered in memory

public static async Task<IReadOnlyList<Order>> ListLatestAsync(DbContext context, int customerId,
    CancellationToken cancellationToken = default)
{
    List<Order> orders = await context.Set<Order>()
        .AsNoTracking()
        .ToListAsync(cancellationToken); // materialized before the filter

    return orders
        .Where(order => order.CustomerId == customerId)
        .OrderByDescending(order => order.PlacedAt)
        .Take(50)
        .ToList();
}

Why: A LINQ operator after ToList, ToArray or AsEnumerable runs in your process on rows that have already left the database. The incorrect method reads the whole table, holds every row in memory and uses none of the database's indexes, to return 50 rows; the correct one sends the filter, the sort and the limit as one SQL statement. The same cost hides behind AsEnumerable() and AsAsyncEnumerable(), which make everything after them run in memory. A test database with a few rows hides the difference until production data arrives.

Exceptions:

  • Some conditions cannot be written as SQL, such as a call to your own method. Apply every operator the database can run first, bound the result (DATA-023), and only then move to memory (AsAsyncEnumerable() streams the rows instead of buffering them).

Scope: LINQ queries over IQueryable sources · Enforced: Manual · Sources: MS-EF-PERF

DATA-023

DO bound every query that returns a list, with Take after a unique OrderBy (Skip and Take for numbered pages) or with a keyset Where on the sort key (Id > lastId) for deep pages.

✅ Correct — a numbered page

private const int MaxPageSize = 100;
private const int MaxPageNumber = 1000; // MaxPageNumber * MaxPageSize stays far below int.MaxValue

public static async Task<IReadOnlyList<Order>> ListPageAsync(DbContext context, int pageNumber, int pageSize,
    CancellationToken cancellationToken = default)
{
    int page = Math.Max(pageNumber, 1); // Page numbers start at 1
    int size = Math.Clamp(pageSize, 1, MaxPageSize); // The caller cannot raise the server maximum

    if (page > MaxPageNumber)
    {
        return []; // Beyond the last page the server serves: an empty page
    }

    return await context.Set<Order>()
        .AsNoTracking()
        .OrderBy(order => order.Id) // Unique sort key
        .Skip((page - 1) * size)
        .Take(size)
        .ToListAsync(cancellationToken);
}

✅ Correct — a keyset page that starts after the last row already shown

private const int MaxPageSize = 100;

public static async Task<IReadOnlyList<Order>> ListAfterAsync(DbContext context, int lastOrderId, int pageSize,
    CancellationToken cancellationToken = default)
{
    int size = Math.Clamp(pageSize, 1, MaxPageSize); // The caller cannot raise the server maximum

    return await context.Set<Order>()
        .AsNoTracking()
        .Where(order => order.Id > lastOrderId)
        .OrderBy(order => order.Id)
        .Take(size)
        .ToListAsync(cancellationToken);
}

❌ Incorrect — no limit

public static async Task<IReadOnlyList<Order>> ListByCustomerAsync(DbContext context, int customerId,
    CancellationToken cancellationToken = default)
{
    return await context.Set<Order>()
        .AsNoTracking()
        .Where(order => order.CustomerId == customerId)
        .ToListAsync(cancellationToken); // returns every matching row
}

❌ Incorrect — a page without an order

private const int MaxPageSize = 100;
private const int MaxPageNumber = 1000; // MaxPageNumber * MaxPageSize stays far below int.MaxValue

public static async Task<IReadOnlyList<Order>> ListPageAsync(DbContext context, int pageNumber, int pageSize,
    CancellationToken cancellationToken = default)
{
    int page = Math.Max(pageNumber, 1);
    int size = Math.Clamp(pageSize, 1, MaxPageSize);

    if (page > MaxPageNumber)
    {
        return [];
    }

    return await context.Set<Order>()
        .AsNoTracking()
        .Skip((page - 1) * size) // no OrderBy: the rows of a page are not defined
        .Take(size)
        .ToListAsync(cancellationToken);
}

Why: The number of rows a query returns depends on the data, so an unbounded query is fast on a test database and slow, or out of memory, in production. A limit also protects the caller, such as a client that receives the whole result over the network. Paging needs a total order: a relational database applies no order unless you ask for one, and an order that is not unique, such as a date alone, can repeat or skip rows between two pages, so end the sort with the key. Skip with a large number makes the database read and discard every skipped row, and rows added or removed between two requests shift the pages. A keyset condition (Id > lastOrderId) starts at the last row already shown, so deep pages cost the same as the first and concurrent changes do not shift them. It supports next and previous but not a jump to page 40, and it is fast only when an index matches the sort key. The EF Core documentation recommends keyset paging over offset paging and advises limiting the result size; requiring a limit on every list query is a house convention built on that advice.

A page size or page number that comes from a request is input, so the limit has to hold whatever the caller sends: cap the size at a server maximum (Math.Clamp(pageSize, 1, MaxPageSize)), require a page number of 1 or more and cap the page number too (MaxPageNumber). Without the size cap, a caller who asks for a million rows per page removes the limit, and a page number below 1 gives a negative offset. A page number above the server maximum returns an empty page, so the offset (page - 1) * size cannot overflow and the cost of a deep offset stays bounded; a caller that must read deep uses the keyset form shown above. The caps are a house convention; the EF Core documentation does not cover request values.

Exceptions:

  • A query that returns at most one row by a unique key, or reads a small fixed reference list such as the countries of a form, needs no limit.
  • A page size that the code fixes itself, as a constant, needs no cap.
  • A batch job that must read every row streams them with AsAsyncEnumerable() instead of buffering a list, and does not page.

Scope: EF Core queries that return a list · Enforced: Manual · Sources: MS-EF-PAGING, MS-EF-PERF

DATA-024

CONSIDER projecting a read-only result into a small type with Select instead of loading whole entities.

✅ Correct

public sealed record OrderSummary(int Id, DateTimeOffset PlacedAt, decimal Total);

public static async Task<IReadOnlyList<OrderSummary>> ListSummariesAsync(DbContext context, int customerId,
    CancellationToken cancellationToken = default)
{
    return await context.Set<Order>()
        .AsNoTracking()
        .Where(order => order.CustomerId == customerId)
        .OrderBy(order => order.Id)
        .Take(100)
        .Select(order => new OrderSummary(order.Id, order.PlacedAt,
            order.Lines.Sum(line => line.Quantity * line.UnitPrice)))
        .ToListAsync(cancellationToken);
}

❌ Incorrect — whole orders and all their lines loaded to read three values

public sealed record OrderSummary(int Id, DateTimeOffset PlacedAt, decimal Total);

public static async Task<IReadOnlyList<OrderSummary>> ListSummariesAsync(DbContext context, int customerId,
    CancellationToken cancellationToken = default)
{
    List<Order> orders = await context.Set<Order>()
        .AsNoTracking()
        .Include(order => order.Lines) // every column of every line is read
        .Where(order => order.CustomerId == customerId)
        .OrderBy(order => order.Id)
        .Take(100)
        .ToListAsync(cancellationToken);

    return orders
        .Select(order => new OrderSummary(order.Id, order.PlacedAt,
            order.Lines.Sum(line => line.Quantity * line.UnitPrice)))
        .ToList();
}

Why: A query that returns entities reads every mapped column, even when the screen shows three. Select makes EF Core read only the columns you name, so less data leaves the database, and a result that holds no entities is never tracked (DATA-020). It also states what the caller needs: the type is the contract. The rule is a suggestion because a query that loads an entity to change and save it needs the entity itself, and a projection that is used once can cost more to write than it saves. The EF Core documentation shows projection for the same reason.

Exceptions:

  • Load the entity when the code changes it and calls SaveChanges.

Scope: Read-only EF Core queries · Enforced: Manual · Sources: MS-EF-PERF

Sources

The keys cited in this chapter are listed on the Sources page.

MS-FDG-TYPES, MS-FDG-MEMBERS, MS-FDG-CAPS, MS-IDE-NAMING, MS-CA, MS-EF, MS-EFA, MS-EF-TRACKING, MS-EF-PERF, MS-EF-RELATED, MS-EF-PAGING, MS-NRT, MS-TAP, DAPPER, OWASP-SQLI, AV.

Previous: Secure Coding · Home · Next: Tooling and Enforcement