Xpandables.Data 11.0.0

dotnet add package Xpandables.Data --version 11.0.0
                    
NuGet\Install-Package Xpandables.Data -Version 11.0.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Xpandables.Data" Version="11.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Xpandables.Data" Version="11.0.0" />
                    
Directory.Packages.props
<PackageReference Include="Xpandables.Data" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Xpandables.Data --version 11.0.0
                    
#r "nuget: Xpandables.Data, 11.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Xpandables.Data@11.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Xpandables.Data&version=11.0.0
                    
Install as a Cake Addin
#tool nuget:?package=Xpandables.Data&version=11.0.0
                    
Install as a Cake Tool

System.Data

Xpandables.Data is a provider-aware ADO.NET data access package for .NET 11.

Installation

dotnet add package Xpandables.Data

Install the ADO.NET provider used by the application:

dotnet add package Microsoft.Data.SqlClient
dotnet add package Npgsql
dotnet add package MySqlConnector
dotnet add package Oracle.ManagedDataAccess.Core
dotnet add package Microsoft.Data.Sqlite

The library resolves a provider by its invariant name through DbProviderFactories, so register the provider's factory once at start-up (an unregistered provider throws ArgumentException when its connection factory is built):

DbProviderFactories.RegisterFactory("Npgsql", NpgsqlFactory.Instance);

A connection string read from configuration names its provider with Provider= (for example Host=db;Database=shop;Provider=Npgsql); the keyword is removed before the string reaches the driver, and a string without it is rejected (InvalidOperationException) rather than handed to SQL Server's client, unless the provider invariant name is passed explicitly (GetFactory(name, providerInvariantName)).

The package brings Xpandables.Generators: the code for [DataRecord] and [DataQueryArgs] types is generated when the application builds. There is nothing else to install.

Supported Providers

Dialect Builder Identifier quoting Pagination
SQL Server MsDataSqlBuilder [Name] OFFSET/FETCH, TOP
PostgreSQL PostgreDataSqlBuilder "Name" LIMIT/OFFSET
MySQL MyDataSqlBuilder `Name` LIMIT/OFFSET
Oracle OracleDataSqlBuilder "Name" OFFSET/FETCH
SQLite LiteDataSqlBuilder "Name" LIMIT/OFFSET

SQLite has no schemas: its dialect writes the bare table name, whatever [Table(Schema = …)] says. new SqliteDialect { SchemaAsAttachedDatabase = true } (with DataBuilder.UseSqlDialect) writes "schema"."table" for tables kept in an attached database. Oracle binds parameters by position: its SQL never repeats a placeholder (a repeated fragment gets parameters of its own), so no BindByName is needed for the SQL it generates. Raw SQL on Oracle binds by position too: list its parameters in placeholder order, each placeholder once, or set OracleConfiguration.BindByName = true at start-up. On Oracle a Guid column is RAW(16), holding Guid.ToByteArray().

Queries

DataQuery supports filtering, projection, joins, grouping, HAVING, ordering, paging, distinct queries, and custom sources — a view, a table-valued function, a derived table or another query.

using System.Data;

DataQuery<Order, OrderSummary> query = DataQuery
    .For<Order>()
    .Where(order => order.CustomerId == customerId
        && order.IsDeleted == false)
    .OrderByDescending(order => order.CreatedAt)
    .Page(pageIndex, pageSize)
    .Select(order => new OrderSummary(order.Id, order.Total));

IAsyncEnumerable<OrderSummary> orders = repository.QueryAsync(query);

Skip/Take/Page need an OrderBy (end it with a unique key so pages are stable); without one, building the SQL throws. Top(n) takes any n rows. DataSqlBuilderOptions.AllowUnorderedPaging lifts the check.

Optional filters should be expressed in the predicate. Closure-only branches are simplified before SQL is emitted:

Status? status = request.Status;

Expression<Func<Account, bool>> filter = account =>
    status == null || account.Status == status.Value;

Boolean expressions, nullable values, enum comparisons, string methods, collection Contains, conditional expressions, and SQL aggregate markers are translated when their expression shape is supported.

Sources

For<T>() reads the entity's table (from [Table] or the type name). For<T>(DataQuerySource) reads from something else, and the source says what it is — the builder never inspects text to decide:

DataQuerySource.Table("vw_ActiveProducts", schema: "reporting")          // quoted by the dialect
DataQuerySource.Raw($"dbo.GetOrders({customerId}, {since})")              // as written; values → @p0, @p1
DataQuerySource.Raw($"[dbo].[Products] WITH (NOLOCK)")                    // as written, no values
DataQuerySource.Subquery($"SELECT * FROM Products WHERE Region = {region}") // parenthesised; values → parameters
DataQuerySource.Subquery(activeProducts)                                   // another IDataQuery, translated with the same builder

Interpolated values in Raw and Subquery are always parameters; the text of the string is yours and is dialect-specific by nature (Oracle wants TABLE(fn()), for instance). Subquery(IDataQuery) merges the inner query's parameters — compiled-query slots included — with the outer statement's. A query with a source can be read and counted but not updated or deleted. The columns a source exposes must match the entity's properties.

Dialects

One translator, DataSqlBuilder, holds every translation rule. A dialect is a SqlDialectDefinition: its data (parameter prefix, limits, boolean literals, paging keyword) and a small set of hooks that write what dialects spell differently — paging, identity inserts, concatenation, LIKE, trimming, date parts, bitwise operators, set membership. The five built-ins are SqlDialectDefinition.SqlServer, .PostgreSql, .MySql, .Oracle and .Sqlite; MsDataSqlBuilder, PostgreDataSqlBuilder, MyDataSqlBuilder, OracleDataSqlBuilder and LiteDataSqlBuilder are DataSqlBuilders over them.

To adjust a dialect, derive from its built-in definition and override what differs. A hook receives its operands as SqlFragments and writes them with SqlWriter.Write: the first write translates the operand, a later one copies it, so a hook can use an operand twice without declaring its parameters twice.

public sealed class CompactSqlServerDialect : SqlServerDialect
{
    // A lower IN-list ceiling, and concatenation written with +.
    public override int MaxInClauseValues => 500;

    public override void WriteConcat(SqlWriter writer, SqlFragment left, SqlFragment right) =>
        writer.Write("(ISNULL(").Write(left).Write(", '') + ISNULL(").Write(right).Write(", ''))");
}

services.AddXData(data => data
    .UseSqlServer(connectionString)
    .UseSqlDialect(new CompactSqlServerDialect()));   // the ConfigureSqlBuilder options apply to it

// Without AddXData: register the builder yourself.
services.AddSingleton<IDataSqlBuilder>(new DataSqlBuilder(new CompactSqlServerDialect()));

A definition is stateless and shared by every statement. DataSqlBuilder itself has no virtual member: deriving from it cannot change what it writes. Each statement is written once into one buffer, so building it costs time linear in its size; parameters are named in the order their placeholders appear in the SQL.

Predicate Composition

The builder is immutable: every call returns a new builder and leaves the one it was called on unchanged, so a base query can be kept in a field and branched per request. Write query = query.Where(...) — a call whose result is dropped changes nothing, and the build fails on it (XDQ004, an error), since a dropped tenant or authorization filter would otherwise go unnoticed. XDQ004 reports the builder returned by any call — a builder method, an extension, a helper — including through ?. and an awaited helper. The "Assign the result" code fix rewrites query.Where(...) into query = query.Where(...) (Fix All available); it is offered when the receiver at the root of the chain is an assignable local, field, settable property or ref/out parameter of the builder's type; not offered otherwise — a by-value parameter (return the builder instead), a helper call, an await, a value-type receiver. A stored task of the builder dropped by await pending; is reported too: assign it (query = await pending;).

Multiple Where calls combine with AND. OrWhere combines with OR and applies to the whole accumulated predicate, so .Where(a).Where(b).OrWhere(c) yields (a AND b) OR c. WhereNot negates its argument and combines with AND. Each has an overload taking a joined entity, so a join can be filtered on:

DataQuery<Order, Order> query = DataQuery
    .For<Order>()
    .InnerJoin<Customer>((order, customer) => order.CustomerId == customer.Id)
    .Where<Customer>((order, customer) => customer.Region == "EU")
    .OrWhere(order => order.Total > 10_000m)
    .Build();

Predicates over different joined entities combine in any order: the calls are merged when the query is built, onto the parameters of the widest lambda. Two lambdas whose joined types cannot share one parameter list (Where<A>(...) then Where<B>(...)) throw NotSupportedException at Build()/Select; write them in one lambda, Where<A, B>(...). Several Having calls combine with AND too.

Paging is Skip, Take, Page(pageIndex, pageSize) (a zero-based index) or Top. Top cannot be combined with the other three: the builder throws InvalidOperationException. A negative value, a page size below 1, or an offset beyond int.MaxValue throws ArgumentOutOfRangeException.

Supported Predicate Shapes

Category Examples
Comparison ==, !=, <, <=, >, >=, ??
Logical &&, \|\|, !, and the non-short-circuit &, \|, ^ over booleans
Boolean bare members, bool? via .Value / .GetValueOrDefault() / a cast, == true, != false
Bitwise &, \|, ^ over integers and [Flags] enums, e.g. (e.Permissions & Read) == Read
Arithmetic +, -, *, /, %, unary -
Null == null, != null, .HasValue, !.HasValue
String Contains, StartsWith, EndsWith, Equals, ToLower, ToUpper, Trim, TrimStart, TrimEnd, Substring, Replace, IndexOf, Concat, Length, IsNullOrEmpty, IsNullOrWhiteSpace
Date .Year, .Month, .Day, .Hour, .Minute, .Second, .Millisecond, .DayOfYear, .DayOfWeek, .Date, AddYears/AddMonths/AddDays/AddHours/AddMinutes/AddSeconds/AddMilliseconds
Math Abs, Ceiling, Floor, Round (a decimal, with MidpointRounding.AwayFromZero), Sqrt, Pow, Exp, Log (natural), Log10, Sign
Set collection.Contains(e.Id), SqlFunctions.In
Markers SqlFunctions.Like, NotLike, Between, In, InTable, InArray, Exists
Subquery SqlFunctions.Scalar(subquery, fallback): COALESCE((SELECT ...), fallback), the value of a one-column, one-row query built into the statement
Aggregates SqlFunctions.Count, CountDistinct, Sum, Avg, Min, Max (in Select and Having of a grouped query)

An expression is translated exactly or the builder throws NotSupportedException: Math.Round needs a decimal and MidpointRounding.AwayFromZero (SQL's ROUND on exact numbers; C# rounds half to even by default, and databases round floating-point values differently), IndexOf takes no start index, MySQL trims a single character only, enum.ToString() over a numeric column is only compared with a constant name, concatenation accepts strings, characters and integers only (SQL formats other values differently from C#), and SqlFunctions.Exists(text) accepts a string literal only.

// The events after the latest snapshot, in one statement.
IDataQuery<Snapshot, long> latest = DataQuery.For<Snapshot>().Where(s => s.OwnerId == id).Select(s => SqlFunctions.Max(s.Version));
IDataQuery<Event, Event> tail = DataQuery.For<Event>()
    .Where(e => e.StreamId == id && e.Version > SqlFunctions.Scalar(latest, -1L))
    .Build();

The subquery of SqlFunctions.Scalar returns one column and at most one row (an aggregate, typically): a second row is the database's error. Its values are parameters of the outer statement. Capture it in a variable: it is then read without compiling the expression.

String and date functions are emitted per dialect, with the meaning of the C# expression:

  • a + b and string.Concat concatenate, a null operand counting as empty (CONCAT, CONCAT_WS('', …) on MySQL, || on Oracle, COALESCE(…, '') || … on SQLite).
  • Without a StringComparison, Contains/StartsWith/EndsWith follow the column's collation, as == does. StringComparison.Ordinal compares bytes (COLLATE Latin1_General_100_BIN2 on SQL Server, COLLATE utf8mb4_bin on MySQL, which therefore needs a utf8mb4 column); an *IgnoreCase comparison compares LOWER/UPPER (ILIKE on PostgreSQL). A comparison held in a variable is read when the query is translated.
  • Trim/TrimStart/TrimEnd with characters trim that set; MySQL trims one character only.
  • e.Status.ToString() == "Active" compares the column with the enum value; a name the enum does not define matches no row.
  • %, & and | become MOD, BITAND and a + b - BITAND(a, b) on Oracle, whose Ceiling and Log10 are CEIL and LOG(10, x).
  • On PostgreSQL a DateTime parameter is timestamp, or timestamptz when its kind is UTC.
  • Oracle reads '' as NULL. A comparison with an empty string (== "", != "", string.Equals(x, ""), a captured empty string) is written as IS NULL / IS NOT NULL, Contains("")/StartsWith("")/EndsWith("") as IS NOT NULL, string.IsNullOrEmpty(x) as x IS NULL and string.IsNullOrWhiteSpace(x) as x IS NULL OR TRIM(x) IS NULL, which is what C# returns. An empty string passed through a compiled-query argument is bound as a parameter, which Oracle compares as NULL.

Two differences are inherent rather than papered over: T-SQL's LEN ignores trailing spaces while LENGTH/CHAR_LENGTH do not, and SQLite date translation relies on dates being stored as ISO-8601 text, which is how this library maps them.

Null Semantics

DataSqlBuilderOptions.NullSemantics says how == and != treat NULL.

  • NullSemantics.Relational (the default) writes a != b as (a <> b), which SQL's three-valued logic evaluates to NULL — and so excludes — when either side is NULL. Where(p => p.Category != "x") therefore drops rows whose Category is NULL, unlike the equivalent in-memory query.
  • NullSemantics.CSharp gives Entity Framework Core's behaviour: comparisons involving a nullable column are expanded to be null-aware.
services.AddXDataSqlBuilderOptions(options => options.NullSemantics = NullSemantics.CSharp);

Column nullability comes from nullable reference type annotations and [Required]; an entity assembly compiled without NRT reports every reference-typed column as nullable, which over-expands the predicate but never returns wrong rows. The expansion applies to WHERE, HAVING and JOIN ... ON alike, so it can change join cardinality.

Under CSharp, a nullable enum compared through ToString() matches what C# returns — a null Nullable<T> gives "":

C# SQL
e.Status.ToString() == "" Status IS NULL
e.Status.ToString() != "" Status IS NOT NULL
e.Status.ToString() == "Active" Status = @p
e.Status.ToString() != "Active" (Status <> @p) OR Status IS NULL

A compiled-query slot is compared NULL-safely when it can hold null: a Nullable<T>, or a reference-typed property of a [DataQueryArgs] type annotated ? (or compiled without nullable annotations). The generator records this at compile time, so the SQL is the same in a trimmed application. The generic DataQueryArgs<T1…> holders, and types registered by hand with DataQueryArgs.Register(placeholder, slotNames), treat every reference slot as nullable.

Large IN Sets

A set is expanded into an inline IN list, split into OR-ed batches at the dialect's limit (SQL Server 2000, Oracle 1000, SQLite 900, PostgreSQL and MySQL 10000). InClauseBatchSize lowers that batch size; it never raises it past the dialect's limit. Batching bounds one IN list, not the command's total parameter count, so several large sets in one predicate can still exceed a provider ceiling.

A statement never carries as many parameters as the database accepts per command (SQL Server 2 100, SQLite 32 766, PostgreSQL and MySQL 65 535): building one throws InvalidOperationException with the count. On SQL Server, a list that would reach the limit is sent as one JSON array read by OPENJSON (SQL Server 2016 or later), so ids.Contains(x.Id) works for any number of ids. The values are sent exactly: a decimal with a nonzero digit past the tenth decimal, a TimeSpan outside 00:00 to 24:00, or a non-finite double is refused with NotSupportedException rather than changed.

At or above CollectionParameterThreshold (200 by default) values, a set can instead be bound as a single parameter:

  • PostgreSQL binds a native array and emits col = ANY(@p0). This needs no schema changes, so the automatic path works out of the box.

  • SQL Server binds a table-valued parameter and emits col IN (SELECT * FROM @p0). This requires a user-defined table type that already exists in the database, bound to one column type — so it is opt-in, either per call site with SqlFunctions.InTable or per element type:

    CREATE TYPE dbo.IntList AS TABLE (Value int NOT NULL PRIMARY KEY);
    GRANT EXECUTE ON TYPE::dbo.IntList TO [app_user];  -- required, and routinely forgotten
    
    services.AddXDataSqlBuilderOptions(options =>
    {
        options.TableTypeNames[typeof(int)] = "dbo.IntList";
        // Xpandables.Data does not reference SqlClient: the application sets the structured type.
        options.ConfigureTableValuedParameter = static (parameter, typeName) =>
        {
            var sql = (Microsoft.Data.SqlClient.SqlParameter)parameter;
            sql.TypeName = typeName;
            sql.SqlDbType = SqlDbType.Structured;
        };
    });
    

    Without a registered type the set degrades to chunked IN lists rather than emitting SQL that would fail at execution; a table type without ConfigureTableValuedParameter throws NotSupportedException when the SQL is built.

  • MySQL, Oracle and SQLite have no equivalent. They always use chunked IN lists, and throw NotSupportedException only for an explicit SqlFunctions.InTable or InArray call.

Set UseCollectionParameters = false to disable the automatic provider-binding path; an explicit SqlFunctions.InTable or InArray still binds one parameter. PostgreSQL binds both as an array; SQL Server has no array, so InArray throws NotSupportedException there unless the set reaches the threshold with a type registered in TableTypeNames.

Row locks and database time

ForUpdateSkipLocked() locks the rows a query reads until the transaction ends and skips the rows another transaction holds: several workers claiming rows at once never take the same row. It runs inside a transaction only: the scope's, or an ambient TransactionScope (the query's connection enlists as it opens); elsewhere it throws InvalidOperationException.

Database SQL
SQL Server WITH (UPDLOCK, READPAST, ROWLOCK) after the table
PostgreSQL, MySQL 8, Oracle FOR UPDATE SKIP LOCKED at the end (Oracle: no Take/Top with it)
SQLite nothing: one writer at a time

DataFunctions.UtcNow() is the database's UTC clock, in predicates and in updater values, so every instance compares times on one clock. On PostgreSQL it is statement_timestamp() (the statement's start, not the transaction's: a lease written late in a long transaction is not already expired), a timestamptz: the columns compared with it must be timestamptz (the event tables are); a timestamp column would be compared through the session's time zone.

await using IDataTransaction transaction = await unitOfWork.BeginTransactionAsync();
List<Job> due = await jobs.QueryAsync(DataQuery.For<Job>()
    .Where(job => job.DueOn <= DataFunctions.UtcNow())
    .OrderBy(job => job.Id).Take(20)
    .ForUpdateSkipLocked().Build()).ToListAsync();
int[] ids = [.. due.Select(job => job.Id)];
await jobs.UpdateAsync(DataQuery.For<Job>().Where(job => ids.Contains(job.Id)).Build(),
    DataUpdater.For<Job>().SetProperty(job => job.LeaseUntil, job => DataFunctions.UtcNow().AddSeconds(30)));
await transaction.CommitAsync();

Compiled Queries

Translating a query to SQL costs a few microseconds per call, and a client-side selector costs a Compile() per reader — hundreds of microseconds. On a hot path, compile the query once and bind its arguments at execution time:

[DataQueryArgs] // Xpandables.Generators emits the IDataQueryArgs implementation
public sealed partial record ProductFilter(decimal MinPrice, int CategoryId, int PageIndex, int PageSize);

private static readonly CompiledDataQuery<Product, ProductFilter, ProductDto> ActiveAbove =
    DataQuery.Compile<Product, ProductFilter, ProductDto>(args =>
        DataQuery.For<Product>()
            .Where(p => p.IsActive && p.Price > args.MinPrice && p.CategoryId == args.CategoryId)
            .OrderBy(p => p.Name)
            .Page(args.PageIndex, args.PageSize)
            .Select(p => new ProductDto(p.Id, p.Name, p.Price)));

await foreach (ProductDto dto in repository.QueryAsync(ActiveAbove, new ProductFilter(100m, categoryId, pageIndex, 20), cancellationToken))
{
    // ...
}

The factory runs once. Inside it, a read of a property of the argument type is emitted as a SQL parameter placeholder; everything else — captured locals, DateTime.UtcNow, literal paging — is evaluated at that moment and stays fixed. The argument type is yours — a partial type marked [DataQueryArgs], a positional record being the natural fit — and Xpandables.Generators (a dependency of this package) emits everything the machinery needs: the IDataQueryArgs implementation, ReadSlots(), and a registration of the slot order with a placeholder factory that calls the real constructor. Nothing about the type is discovered at run time, so there is no reflection to trim and no behaviour that differs under Native AOT. A type written without the generator is registered by hand with DataQueryArgs.Register<T>(placeholder, slotNames); an unregistered type is rejected by Compile (InvalidOperationException). A type has at most DataQueryArgs.MaxArity (64) slots. For a one-off, the ready-made DataQueryArgs<T1, …, T8> holders expose Value / Value1…Value8 instead:

DataQuery.Compile<Product, decimal, ProductDto>(args =>
    DataQuery.For<Product>().Where(p => p.Price > args.Value).Select(p => new ProductDto(p.Id, p.Name, p.Price)));

The SQL is produced the first time the query meets an IDataSqlBuilder and reused for that builder's lifetime; Prepare(builder) produces it eagerly so an unsupported construct fails at start-up.

Bind(...) returns an IBoundDataQuery<TData, TResult> accepted by every repository method, so QuerySingleAsync, QueryPagedAsync, DeleteAsync and UpdateAsync work too. The extension methods QueryAsync, QueryFirstOrDefaultAsync, QuerySingleOrDefaultAsync and CountAsync take the compiled query and its arguments directly.

A slot can stand wherever a scalar constant can: comparisons, arithmetic, Contains/StartsWith/EndsWith patterns (wildcards are escaped at bind time), enums against text columns. An int slot can also be passed to Skip, Take, Top and Page, which then emit OFFSET @p ROWS / LIMIT @p / TOP (@p) instead of a literal; Page(args.PageIndex, args.PageSize) binds the offset as index * size, so both values must be arguments (or both literals). It cannot supply the set of an IN clause — the SQL text depends on the number of values. A nullable slot bound to null compares like a null constant: p.ParentId == args.ParentId matches the rows whose ParentId is NULL. An unbound placeholder that reaches a command throws rather than running with a missing value.

Outside an expression an int slot evaluates to a reserved negative marker (DataQueryArgs.PagingMarker), which is how Skip(args.Value) is recognised; compiled.Template.Skip shows that marker, while a bound query reports the real value. Adding to or subtracting from a slot (Take(args.Size - 1)) is detected and throws; a product of slots (Skip((args.Page - 1) * args.Size)) cannot be told from a legal value — use Page(args.Index, args.Size) or pass the computed value as an argument.

The build checks the factory (CompiledDataFactoryAnalyzer in Xpandables.Generators). A slot the factory evaluates instead of leaving it to an expression holds its placeholder on every execution, and is an error (XDQ005): kept in a local that an expression captures (var min = args.MinPrice; Where(p => p.Price > min)), passed to a method (Filter(args.MinPrice)), or tested in a condition (if (args.MinPrice > 0)). Read it directly inside the expression, or pass the argument object itself, whose properties stay slots wherever an expression reads them. A value that changes between calls — DateTime.UtcNow, Guid.NewGuid(), TimeProvider.GetUtcNow() — is fixed by the first statement, and is a warning (XDQ006): make it an argument. A member of your own, such as _clock.Now, cannot be told from a value fixed on purpose and is not reported.

What the generator emits

For a [DataQueryArgs] partial type, the generator adds the IDataQueryArgs implementation, a ReadSlots() listing the public properties in declaration order (kept if you wrote one), and a module initializer calling DataQueryArgs.Register<T>(placeholder, slotNames, nullableSlots) with a factory that runs the real constructor and puts the paging marker in every int slot. It reports an error at build time when the type is not partial (XDQ001), is generic or abstract (XDQ002), or has an int property that is neither a constructor parameter nor settable (XDQ003) — the one case where Skip(args.X) could silently read 0. Compile still checks, once, that ReadSlots() and the registration agree on the slot order.

Measured with BenchmarkDotNet (System.Data.Benchmarks, .NET 10, SQL Server dialect, 3-term predicate with ordering and paging):

Operation Per call Allocated
BuildSelect on a pre-built DataQuery 2.5 µs 6.2 KB
Bind(4 args, paging included) + BuildSelect on a compiled query 96 ns 528 B
Bind(ProductFilter record) + BuildSelect on a compiled query 99 ns 576 B
Bind([DataQueryArgs] generated record) + BuildSelect on a compiled query 104 ns 576 B
Map 100 rows, client-side selector, query rebuilt per call 203 µs 39.9 KB
Map 100 rows, client-side selector, compiled or static query 22 µs 31.3 KB

The second pair also applies to a plain DataQuery kept in a static readonly field: the mapper shares the compiled selector across readers as long as the same expression instance is reused.

Reading the arguments of a 12-property record at Bind (ArgsReadBenchmarks) costs about 40 ns whether ReadSlots() is generated or hand-written; the 400 B allocated are the array and the boxed values, which DbParameter.Value needs anyway. No argument is read by reflection.

Compiled Updates

A compiled query keeps its SELECT, COUNT, EXISTS and DELETE statements, but not its UPDATE: the updater carries its own values, so the statement is translated again on every call. A compiled update fixes the filter and the property updates together, with argument slots in both, and keeps the UPDATE statement:

private static readonly CompiledDataUpdate<Product, int, decimal, DateTime> Reprice =
    DataUpdater.Compile<Product, int, decimal, DateTime>(args => (
        DataQuery.For<Product>().Where(p => p.IsActive && p.CategoryId == args.Value1).Build(),
        DataUpdater.For<Product>()
            .SetProperty(p => p.Price, p => p.Price * args.Value2)
            .SetProperty(p => p.UpdatedAt, p => args.Value3)));

int changed = await repository.UpdateAsync(Reprice, categoryId, 1.1m, DateTime.UtcNow, cancellationToken);

DataUpdater.Compile takes the same argument forms as DataQuery.Compile: none, the DataQueryArgs<T1, …, T8> holders, or a [DataQueryArgs] type of your own. The factory runs once, and the update is checked then: a filter with a join, an ordering, a grouping, Having, Distinct or paging throws NotSupportedException; a custom DataQuerySource or an updater without SetProperty throws InvalidOperationException. The statement is produced the first time the update meets an IDataSqlBuilder and reused for that builder's lifetime; Prepare(builder) produces it now, which also checks the argument slots against the arity.

An argument written to a column goes through the computed overload, SetProperty(p => p.Status, p => args.Value), which emits a parameter typed like the column (an enum stored as text binds as its name, a data value as its primitive). The constant overload evaluates its value once, so SetProperty(p => p.Status, args.Value) would write the placeholder on every execution: the build reports it as an error (XDQ005), as it does an argument kept in a local or passed to a method that builds the updater. Every other value — constants, captured locals, DateTime.UtcNow, even inside a computed value — is fixed when the statement is first produced, so a value that changes between executions, such as a timestamp, is an argument (DateTime.UtcNow and its kind are reported as a warning, XDQ006). The updater of a compiled update is a frozen copy (IsFrozen): SetProperty on it throws, and changing the updater given to the factory afterwards does not reach the statement.

Bind(...) returns a BoundDataUpdate<TData>, which IDataRepository<TData>.UpdateAsync(update) executes; the generated UpdateAsync extensions take the compiled update and its arguments directly. Only a compiled update creates one, so its statement runs without being checked again. DataRepository<TData> runs the cached statement through the command interceptors like any update, but not through UpdateAsync(query, updater): a subclass that overrides that method (a tenant filter, an audit) overrides UpdateAsync(BoundDataUpdate<TData>) too, for example with UpdateAsync(update.Query, update.Updater, cancellationToken). Another implementation of IDataRepository<TData> gets that same default, which translates the bound filter and the updater again into the same statement.

Operation (QueryBenchmarks, SQL Server dialect) Per call Allocated
BuildUpdate, query and updater built per call 4.5 µs 7.4 KB
BuildUpdate, compiled query and an updater built per call 4.5 µs 6.3 KB
Bind(2 args) + BuildUpdate on a compiled update 66 ns 296 B

Data Records

Every type the library reads from or writes to a table — an entity, or a type read from raw SQL — is a data record, declared with [DataRecord]:

[DataRecord]
[Table("Orders", Schema = "sales")]
public sealed class Order
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public string Customer { get; set; } = "";

    [ConcurrencyCheck]
    public int Version { get; set; }
}

// A type you do not own:
[assembly: DataRecord(typeof(ThirdParty.Customer))]

Xpandables.Generators reads the attributes when the project builds and generates the record's metadata — table, columns, keys, constructors — and its row reader, registered by a module initializer. Nothing is discovered by reflection at run time, so the library behaves the same whether or not the application is trimmed or published with Native AOT. Using a type that is not a data record throws InvalidOperationException ('Order' is not a data record: mark it [DataRecord] or add [assembly: DataRecord(typeof(Order))].). Declare an assembly-level record in the assembly that uses it: its registration runs when that assembly's code first runs.

The type does not need to be partial: the reader calls a public constructor, assigns settable properties, and reaches init, required and non-public setters through UnsafeAccessor. The generator reports at build time:

Id When
XDR001 the type has no public constructor the reader can call
XDR002 a mapped property's type is not a column type (mark it [NotMapped])
XDR003 the type is not a class or a struct; is generic (or nested in a generic type), abstract or static; generated code cannot reach it (a private nested or file-local type); it, or a mapped property (the property, its getter, its type or the type declaring it), is [Obsolete] as an error (mark such a property [NotMapped]); or it is a struct with required members and no public [SetsRequiredMembers] constructor
XDR004 a [ConcurrencyCheck] property is not an int/long with a set accessor, or is declared on a struct
XDR005 (warning) a database-generated column has no setter: it is not refreshed after writes
XDR006 two properties map to the same column

Projections — anonymous types, DTOs — need no declaration: they are built from the selector itself. In a trimmed or Native AOT application prefer a constructor (Select(o => new OrderView(o.Id, o.Customer))): the C# compiler builds an anonymous type or an object initializer in an expression tree with Expression.New(…, members) and Expression.Bind(…), which .NET marks [RequiresUnreferencedCode], so the warning appears in your own code whatever the LINQ provider; the query still runs.

A record reads each column by name, ignoring case: a constructor parameter or a property by its [Column] name, then by its own name. When a result set has two columns of the same name (a raw SELECT over a join), the first occurrence binds. A column whose provider type is the member's type (or its underlying type) is read with the reader's typed getter (GetInt32, GetGuid, GetDecimal, …), without boxing the value; any other column is read as an object and converted. A record with a public parameterless constructor is built with it; otherwise the reader calls the widest public constructor whose every parameter matches a column, and throws InvalidOperationException when none does.

The repository asks its IDataSqlMapper for a row mapper once per result set (CreateRowMapper): the columns, the record's plan and a compiled projection are resolved there, and each row is mapped without looking them up again. A custom mapper that implements only MapToResult inherits a CreateRowMapper that calls it for every row.

Value Objects

A value object stored in one column — an identifier, an e-mail address — is a data value, declared with [DataValue]:

[DataValue]
public readonly record struct OrderId(Guid Value);

[DataRecord]
public sealed class Order
{
    [Key]
    public OrderId Id { get; set; }

    public OrderId? Parent { get; set; }
}

// A type you do not own:
[assembly: DataValue(typeof(ThirdParty.Email))]

The type has one scalar value, its primitive: the parameter of a public one-parameter constructor (or of a public static From/Create method returning the type), read back through the public property of that type (Value here). The primitive is a column type (not another data value). The generator registers each type's conversions with DataValues from a module initializer, and reports at build time:

Id When
XDV001 the type has no single scalar value (constructor or factory, and property)
XDV002 the primitive is not a column type
XDV003 the type is not a class or a struct; is generic (or nested in a generic type), abstract or static; generated code cannot reach it; or it, its constructor or factory, its value property or its primitive is [Obsolete] as an error

A data value is then a column (a key too), stored as its primitive: DataColumnMetadata.ClrType is the primitive and ValueType the declared type. It works everywhere a scalar does, and is always bound as its primitive:

DataQuery.For<Order>().Where(o => o.Id == id);              // WHERE Id = @p0 (a Guid)
DataQuery.For<Order>().Where(o => ids.Contains(o.Id));      // IN (@p0, @p1)
DataQuery.For<Order>().Where(o => o.Parent == null);        // IS NULL
DataQuery.For<Order>().Where(o => o.Id.Value == guid);      // the value property is the column
DataQuery.For<Order>().Select(o => o.Id);                   // read back as OrderId
repository.QueryRawAsync<OrderId>("SELECT Id FROM Orders");

A compiled-query argument of a data value type is bound as its primitive. An operator the type defines (<, >) is not translated — it may mean anything — and throws NotSupportedException: compare the value property instead. A wrapper type that is not a data value reaches the provider unchanged (some providers bind custom types through their own type handlers); its conversion operators are never called.

Table and Column Metadata

TableAttribute supplies the table and schema. ColumnAttribute.Name supplies the column name, and the builder and the mapper resolve columns with the same rule: the [Column] name first, then the property name; a [NotMapped] property is never selected nor bound. ColumnAttribute.TypeName supplies the target SQL storage type when parameter conversion depends on it. Inserts skip [DatabaseGenerated(Identity)], [DatabaseGenerated(Computed)] and [Timestamp] columns. [Key] marks the key — several properties for a composite key — and without one a property named Id is the key. A column's nullability comes from the nullable annotations ([Required] makes it non-nullable; a reference type in a #nullable disable context is nullable).

An enum is stored as its underlying integer, or as its name in a text column declared with TypeName:

[Table("Accounts", Schema = "Registration")]
public sealed class Account
{
    [Column("Status", TypeName = "varchar(50)")]
    public AccountStatus Status { get; set; }
}

The SQL builder uses this metadata consistently for predicates, joins, inserts, updates, and Contains values.

DateOnly binds as date and TimeOnly as time (Oracle: DATE and INTERVAL DAY TO SECOND). A string property whose [Column(TypeName = …)] starts with varchar or char, or marked [Unicode(false)], binds as a single-byte string, so SQL Server compares it with its varchar index instead of converting every row. SQL Server string parameters have a fixed size (4000, 8000 single-byte, or max), so one plan serves every value length.

A row maps to a scalar (primitives, enums, string, decimal, Guid, DateTime, DateTimeOffset, DateOnly, TimeOnly, TimeSpan, byte[], Int128, UInt128, Half, and their nullable forms) or to a data record whose constructor parameters and writable properties match the columns; a NULL column leaves the property's initial value. A result type that receives no column throws InvalidOperationException; a NULL for a non-nullable value-type constructor parameter, and any value that cannot be converted, throw InvalidCastException.

Repository Operations

IAsyncEnumerable<Order> query = repository.QueryAsync(
    DataQuery.For<Order>().Build());

long count = await repository.CountAsync(
    DataQuery.For<Order>().Where(order => order.CustomerId == customerId).Build());

DataUpdater<Order> updater = DataUpdater.For<Order>()
    .SetProperty(order => order.Status, OrderStatus.Paid)
    .SetProperty(order => order.UpdatedAt, DateTime.UtcNow);

DataQuery<Order, Order> target = DataQuery.For<Order>()
    .Where(order => order.Id == orderId)
    .Build();

await repository.UpdateAsync(target, updater, cancellationToken);
await repository.DeleteAsync(target, cancellationToken);

UpdateAsync(query, updater) and DeleteAsync(query) take a filter: the statement is written from the query's predicate (UPDATE … SET … WHERE …, DELETE FROM … WHERE …), and a query without Where changes every row. A query that also has a join, an ordering, a grouping, Having, Distinct or paging (Skip, Take, Top, including a compiled query's paging argument) throws NotSupportedException, because a plain UPDATE/DELETE would reach the rows that query excludes. A query with a DataQuerySource and an updater without SetProperty throw InvalidOperationException.

To change a limited or ordered set of rows, select their keys with that query, then filter on the keys:

List<int> oldest = [];
await foreach (int id in repository.QueryAsync(
    DataQuery.For<Order>().OrderBy(order => order.CreatedAt).Take(10).Select(order => order.Id), cancellationToken))
{
    oldest.Add(id);
}

await repository.DeleteAsync(
    DataQuery.For<Order>().Where(order => oldest.Contains(order.Id)).Build(), cancellationToken);

The repository also supports QueryFirstAsync/QueryFirstOrDefaultAsync (which request one row), QuerySingleAsync/QuerySingleOrDefaultAsync (two rows), ExistsAsync (EXISTS, no count), raw SQL queries, batch inserts and identity retrieval. A compiled query keeps its prepared SQL: it is read without the row limit, and ExistsAsync sends its prepared EXISTS.

QueryAsync and QueryRawAsync check their arguments when they are called. The SQL is built, reading the values the query captured, and the command sent each time the sequence is enumerated; the reader is closed when the enumeration ends or stops early.

  • QueryPagedAsync reads the total from a COUNT(*) OVER() column of the page itself; DISTINCT, GROUP BY and compiled queries count separately.
  • QueryRawAsync(sql, selector) materialises the entity from the caller's SQL, then runs the selector on it; ExecuteAsync(sql, parameters) runs a raw INSERT/UPDATE/DELETE and returns the affected rows.
  • InsertAsync<TIdentity> returns the generated key converted to TIdentity (OUTPUT INSERTED, RETURNING, SELECT LAST_INSERT_ID() on MySQL, an output parameter on Oracle).
  • InsertAsync(entities) splits the batch into statements within the builder's MaxParametersPerCommand and MaxRowsPerInsert; several statements run in a transaction of their own unless the caller has one.
  • A null value an insert or an update writes is the NULL literal: it binds no parameter, so a statement carries only the values it needs.

An IDataCommandInterceptor observes every command: an exception it throws never changes the command's outcome. The registered chain logs it (see Interceptors); an interceptor handed straight to a repository's constructor has its failure written to System.Diagnostics.Trace.

Several queries at once

QueryAsync(cancellationToken, params IDataQuery[] queries) reads two or more queries — of the repository's data or of any other — and returns a DataResults that gives each query's rows back by the query itself:

IDataQuery<Order, Order> open = DataQuery.For<Order>().Where(order => order.Status == "open").Build();
IDataQuery<Customer, string> names = DataQuery.For<Customer>().Where(c => c.Region == region).Select(c => c.Name);

DataResults results = await orders.QueryAsync(cancellationToken, open, names);
IReadOnlyList<Order> openOrders = results.Of(open);
IReadOnlyList<string> customerNames = results.Of(names);

Where the provider batches commands (DbConnection.CanCreateBatch: Npgsql, SqlClient, MySqlConnector) the queries travel in one DbBatch, one round trip; elsewhere (SQLite, ODP.NET) they run one after the other with the same results. Each query is observed by the interceptors as if it ran alone. Fewer than two queries, or one given twice, throw ArgumentException; a null query ArgumentNullException; Of with a query that was not read, ArgumentException.

Stored procedures, output parameters and several result sets

A hand-written command is a DataCommand: SQL text (DataCommand.Text(sql, parameters)) or a stored procedure (DataCommand.Procedure(name, parameters), the name as the database knows it, schema included). Its parameters are SqlParameters; a parameter whose Direction is Output, InputOutput or ReturnValue is read back by name. DataCommand checks its arguments when it is created (ArgumentException): the text or name is not blank, parameter names are unique (ignoring case and a leading @, : or ?), there is at most one ReturnValue, and an Output or ReturnValue parameter, or an InputOutput one whose value is null, has a Type (or a Configure), because the provider would otherwise guess its type. A string or byte[] output (Output or InputOutput) also needs a Size large enough for the value that comes back: SqlClient refuses a size of 0 and ODP.NET fails on a buffer too small (ORA-06502). This is not checked; Npgsql and MySqlConnector do not need it.

The name of a procedure is sent as SQL: never build it from user input. It may be schema-qualified or quoted, and is not checked beyond being not blank.

Four members are dedicated to procedures; each is shorthand for the matching DataCommand member given DataCommand.Procedure(name, parameters): ExecuteAsync, QueryRawAsync, QueryMultipleAsync. The rows below are read as a data record:

[DataRecord]
public sealed record Number(int Value);
// Outputs and the return value (SQL Server).
DataCommandResult result = await repository.ExecuteProcedureAsync("dbo.XpCustomer",
[
    new SqlParameter { Name = "id", Value = 5 },
    new SqlParameter { Name = "total", Direction = ParameterDirection.Output, Type = typeof(int) },
    new SqlParameter { Name = "ret", Direction = ParameterDirection.ReturnValue, Type = typeof(int) },
]);
int total = result.GetOutput<int>("total");
int status = result.GetOutput<int>("ret");

// One result set, each row read as a record, or by a mapper.
List<Number> rows = await repository
    .QueryProcedureAsync<Number>("dbo.XpRows", [new SqlParameter { Name = "n", Value = 3 }])
    .ToListAsync();
List<int> values = await repository
    .QueryProcedureAsync("dbo.XpRows", reader => reader.GetInt32(0), [new SqlParameter { Name = "n", Value = 3 }])
    .ToListAsync();

// Several result sets, then the outputs.
await using DataResultSets sets = await repository.QueryProcedureMultipleAsync("dbo.XpCustomer",
[
    new SqlParameter { Name = "id", Value = 5 },
    new SqlParameter { Name = "total", Direction = ParameterDirection.Output, Type = typeof(int) },
]);
IReadOnlyList<Number> first = await sets.ReadAsync<Number>();
IReadOnlyList<Number> second = await sets.ReadAsync<Number>();
DataCommandResult outputs = await sets.CompleteAsync();

QueryProcedureAsync takes input parameters only (an output throws ArgumentException when the method is called: use ExecuteProcedureAsync or QueryProcedureMultipleAsync).

The DataCommand members take SQL text as well as a procedure:

Member Gives back
ExecuteAsync(DataCommand) DataCommandResult: RowsAffected, and GetOutput<T>(name) for each output, input-output and return-value parameter. Rows the command returns are not read
QueryMultipleAsync(DataCommand) DataResultSets: every result set, read in order, then the outputs
QueryRawAsync<T>(DataCommand) (and with a mapper) The rows of the one result set, lazily
// An Oracle anonymous block with an output.
DataCommandResult result = await repository.ExecuteAsync(DataCommand.Text(
    "BEGIN :total := 41 + 1; END;",
    new SqlParameter { Name = "total", Direction = ParameterDirection.Output, Type = typeof(int) }));
int total = result.GetOutput<int>("total"); // 42

// Several SELECTs in one round trip.
await using DataResultSets sets = await repository.QueryMultipleAsync(DataCommand.Text(
    "SELECT Id, Name FROM Customers WHERE Region = @region; SELECT Id, Total FROM Orders WHERE Region = @region",
    new SqlParameter { Name = "region", Value = region }));
IReadOnlyList<Customer> customers = await sets.ReadAsync<Customer>();
IReadOnlyList<int> orderTotals = await sets.ReadAsync(reader => reader.GetInt32(1));
_ = await sets.CompleteAsync();

DataResultSets:

  • ReadAsync<T>() reads the next result set that has columns (a count, or MySQL's trailing status, is skipped), mapping its rows as QueryRawAsync<T> does; ReadAsync(map) calls map on the reader for each row, and map must not keep it. Reading past the last result set throws InvalidOperationException.
  • CompleteAsync() checks that no result set is left (one would be lost: InvalidOperationException), closes the reader and gives back the DataCommandResult; the provider fills the outputs only then.
  • The connection is busy until the DataResultSets is disposed: another command on the same connection fails on a provider without multiple active result sets. Dispose it (await using); disposing without CompleteAsync closes the reader and checks nothing.
  • It is not thread-safe: one call at a time. A failure of the command or of the mapper, or a cancellation, closes it, and a later call throws ObjectDisposedException. The command is observed once, as a single command.
  • DataResultSets.FromMemory(new DataCommandResult(rowsAffected, outputs), firstSet, secondSet) builds result sets from rows already in memory, for a test double of IDataRepository<T>: each ReadAsync<T> gives back the next set's rows (they must already be T; a mapper is not called) and CompleteAsync gives back the DataCommandResult.

QueryRawAsync and ExecuteAsync(string) read one result set and no outputs, and refuse to lose either: a parameter that is not Input throws ArgumentException (use ExecuteAsync(DataCommand) or QueryMultipleAsync) — when QueryRawAsync is called, and through the task of ExecuteAsync(string), an async method whose argument and support errors all arrive through its task — and a further result set with columns after the last row of QueryRawAsync throws InvalidOperationException pointing to QueryMultipleAsync (a consumer that stops early never reaches the check).

SqlParameter.Configure sets what the provider needs and SqlParameter has no member for, after the library's own settings. An Oracle SYS_REFCURSOR output is a result set of the reader:

var cursor = new SqlParameter
{
    Name = "rows",
    Direction = ParameterDirection.Output,
    Configure = static parameter => ((OracleParameter)parameter).OracleDbType = OracleDbType.RefCursor,
};

await using DataResultSets sets = await repository.QueryProcedureMultipleAsync("XpCursor", [cursor]);
IReadOnlyList<Number> numbers = await sets.ReadAsync<Number>();
_ = await sets.CompleteAsync();

Procedures are logged and traced by name (db.stored_procedure.name, a span named {operation} {procedure}), and the savepoint statements waiting in a transaction are sent before a procedure runs.

Provider Procedure Result sets Outputs
SQL Server RPC on the name; parameters bind by name, given without @; the return value is a ReturnValue parameter From the reader After the reader closes
MySQL CALL name(…), built by MySqlConnector from the routine's metadata, which needs EXECUTE on the routine (or its database) and no more; parameters bind by name From the reader; the trailing status is skipped After the reader closes
Oracle BEGIN name(…); END;; ODP.NET binds by position (see below) Implicit results (DBMS_SQL.RETURN_RESULT) and SYS_REFCURSOR outputs, in order After the reader closes
PostgreSQL CALL name(…) through Npgsql, which binds IN, INOUT and OUT parameters by name, in any order A procedure returns no rows: read a function with SELECT * FROM fn(@a) as text INOUT and OUT values, through ExecuteProcedureAsync or ExecuteAsync
SQLite None: a procedure is refused with NotSupportedException, thrown when QueryProcedureAsync or QueryRawAsync is called, and as a faulted task from ExecuteProcedureAsync, QueryProcedureMultipleAsync, ExecuteAsync(DataCommand) and QueryMultipleAsync Several statements in one text, through QueryMultipleAsync None

A PostgreSQL procedure returning refcursors is not read automatically; read a set-returning function with QueryRawAsync<T>(DataCommand.Text("SELECT * FROM fn(@a)", …)), or several with QueryMultipleAsync.

Oracle parameter order

ODP.NET binds a command's parameters by position unless OracleCommand.BindByName is set. A procedure called with its parameters in another order than its declaration raises no error and returns a wrong result. Either give the parameters in the procedure's declaration order, or set BindByName for the database with ConfigureCommands.

ConfigureCommands

DataBuilder.ConfigureCommands(Action<DbCommand>) sets a provider property the library does not write. The action runs on every command of the database, after its transaction is set: the SQL the repositories build, raw text, procedures, the commands of IDataConnectionScope.CreateCommand() and the one that sends waiting savepoint statements. A second call adds its action after the first. Cast the command to the provider's type:

services.AddXData(data => data
    .UseOracle(connectionString)
    .ConfigureCommands(static command => ((OracleCommand)command).BindByName = true)
    .AddRepository<Order>());

An exception the action throws reaches the caller of the operation, and the command is disposed. The queries of QueryAsync(queries) that travel in a DbBatch are not configured: a batch holds DbBatchCommands, not commands.

Update and delete by entity

Order order = await repository.QuerySingleAsync(DataQuery.For<Order>().Where(o => o.Id == id).Build());
order.Customer = "Ann";

// UPDATE "sales"."Orders" SET "Customer" = @p0, "Version" = "Version" + 1 WHERE "Id" = @p1 AND "Version" = @p2
await repository.UpdateAsync(order, cancellationToken);
await repository.DeleteAsync(order, cancellationToken);

The row is matched by every key and every concurrency token the entity holds. A [ConcurrencyCheck] column is a version number (int or long): the statement increments it and, on success, the repository increments the entity's, so the same instance can be updated again. The increment is made in memory: a transaction rolled back afterwards does not undo it, so reload the entity after a rollback. When no row matches — it was deleted, or changed since it was read — the call throws DBConcurrencyException. A record without a key throws InvalidOperationException before any SQL runs.

The columns the database generates are read back into the entity by the statement that writes it: after InsertAsync(entity) the identity, the [DatabaseGenerated(DatabaseGeneratedOption.Computed)] columns and the [Timestamp] row version; after UpdateAsync(entity) the computed columns and the row version. The same instance can therefore be updated again. InsertAsync<TIdentity>(entity) returns the identity and sets it on the entity too.

Dialect Insert Update
SQL Server INSERT … OUTPUT INSERTED.[Id], INSERTED.[Stamp] VALUES (…) UPDATE … SET … OUTPUT INSERTED.[Stamp] WHERE …
PostgreSQL, SQLite INSERT … VALUES (…) RETURNING "Id", "Upper" UPDATE … WHERE … RETURNING "Upper"
Oracle INSERT … VALUES (…) RETURNING "Id", "Upper" INTO :p5, :p6 UPDATE … WHERE … RETURNING "Upper" INTO :p4
MySQL INSERT …; SELECT Id, Upper FROM t WHERE Id = LAST_INSERT_ID() UPDATE … WHERE …; SELECT Upper FROM t WHERE <key> AND ROW_COUNT() > 0

A generated column needs a setter to be refreshed (an init or private setter is enough); without one the build warns XDR005. A record without generated columns gets a plain INSERT/UPDATE; on MySQL, so does the insert of a record with neither an identity nor a key (the row cannot be selected again), whose generated columns are then not read back. SQL Server rejects OUTPUT without INTO on a table with an enabled trigger: such a table cannot use insert or update by entity when it has generated columns. SQLite reports a stored generated column in RETURNING; a value a trigger writes is not.

Upsert

UpsertAsync inserts an entity, or updates the row with its key — or with the unique properties a conflict key selects:

await stock.UpsertAsync(new StockItem { Sku = "A-1", Qty = 5 });
await tags.UpsertAsync(newTags, tag => tag.Code, cancellationToken: token);   // matched on the unique Code

The update writes every column that is not a key, not generated and not a concurrency token, and increments each [ConcurrencyCheck] version; a [Timestamp] row version is left to the database, and the row is not matched on the token the entity holds. SQL Server (MERGE … WITH (HOLDLOCK)) and Oracle write a MERGE, PostgreSQL and SQLite INSERT … ON CONFLICT … DO UPDATE, MySQL (8.0.19 and later) INSERT … AS new_row ON DUPLICATE KEY UPDATE — which matches every unique key of the table, so a conflict key does not narrow it, and counts an updated row twice. The result is the rows the provider reports; generated columns are not read back. A conflict key on a generated column throws InvalidOperationException, one that selects anything but properties NotSupportedException. The entities of one call hold distinct conflict keys; past the database's limits they run as several statements in one transaction the call owns when none is active.

Unit of Work and Transactions

Inside a DI scope (an HTTP request, a message), the unit of work and every repository share one IDataConnectionScope — one connection, one transaction. The container owns the scope and disposes it; a transaction still open at that point is rolled back.

public sealed class PlaceOrder(IDataUnitOfWork unitOfWork, IDataRepository<Order> orders)
{
    public async Task HandleAsync(Order order, OrderLine line, CancellationToken cancellationToken)
    {
        await using IDataTransaction transaction = await unitOfWork.BeginTransactionAsync(cancellationToken: cancellationToken);

        await orders.InsertAsync(order, cancellationToken);                        // injected: same connection
        await unitOfWork.GetRepository<OrderLine>().InsertAsync(line, cancellationToken);

        await transaction.CommitAsync(cancellationToken);
    }
}

Disposing a transaction that was not committed rolls it back, so await using is the whole error path.

  • Nesting joins. BeginTransaction(Async) while a transaction is active returns a participant of it: its commit does nothing, and its rollback — or its disposal without a commit — marks the outer transaction rollback-only. The outer commit then rolls back and throws InvalidOperationException, so work an inner part refused is never committed. A participant cannot change the isolation level of the running transaction.
  • Isolation. The default is IsolationLevel.Unspecified, the provider's own default; pass a level to choose one.
  • Savepoints. IDataConnectionScope.BeginSavepointAsync(name?) (unitOfWork.ConnectionScope from a unit of work) rolls back part of a transaction: rolling the savepoint back undoes only the work done since — including an inner transaction that rolled back after it, whose rollback-only mark it clears — and the transaction can still commit; committing the savepoint releases it, and disposing it without either rolls back to it. Without an active transaction it begins one. A name holds letters, digits and underscores, does not start with a digit, and is checked against the dialect's limit (SQL Server 32, PostgreSQL 63, MySQL 64, Oracle 128 characters); otherwise ArgumentException. A savepoint inside an ambient TransactionScope throws NotSupportedException (it needs a local transaction). On PostgreSQL the SAVEPOINT and its RELEASE are sent with the next command instead of a round trip each; a savepoint released or rolled back before any command sends nothing, and a command made with CreateCommand() (whose text the caller writes) sends a waiting savepoint first.
  • TransactionScope. Inside an ambient System.Transactions transaction the connection enlists in it; BeginTransaction(Async) returns a handle whose commit does nothing (call Complete() on the scope) and whose rollback — or disposal without a commit — aborts the ambient transaction. A connection opened before the scope is enlisted then; Microsoft.Data.Sqlite cannot enlist and throws NotSupportedException. HasActiveTransaction is true while that ambient transaction is active.
  • After the commit. transaction.OnCommitted(callback) runs the callback once the work is durable: after this transaction's commit, or after the outermost one for a participant, a savepoint or an ambient transaction; never when it rolls back (a rollback to a savepoint drops the callbacks registered after it). Callbacks run after the commit, one after the other, in registration order; registered once the outermost transaction committed, one runs at once; one that throws is logged and does not fail the commit.
  • One command at a time. A scope wraps one ADO.NET connection, which runs one command at a time (MARS is provider-specific): do not run queries of the same scope concurrently.

A commit is never cancelled by the token passed to CommitAsync: once sent, a cancelled commit would have an unknown outcome. When the database does not confirm a commit (the connection dropped while committing), DataCommitOutcomeUnknownException is thrown: the transaction may or may not be committed, no after-commit callback runs, and the work must not be run again blindly — read the data back first. The library does not roll it back; the provider transaction is disposed, which on some providers aborts what the server still holds open. Once a commit succeeded, a failure while completing it (disposing the provider transaction, releasing the connection) is traced and never thrown: the commit is durable, and its callbacks still run. OnCommitted(Func<CancellationToken, ValueTask>) registers asynchronous work after the commit; CommitAsync awaits it. A callback run by Commit(), by an ambient completion, or registered after the outermost commit is waited on synchronously: on a single-threaded SynchronizationContext (a UI thread) it deadlocks unless its awaits use ConfigureAwait(false). A callback that fails is logged at Error (logger category System.Data.DataTransaction) and never fails the commit; scopes created by DI, IDataConnectionScopeFactoryProvider included, log through the container's ILoggerFactory.

Outside DI, build the unit of work from a scope you own, or let DataUnitOfWorkFactory create both:

await using IDataConnectionScope scope = scopeFactory.CreateScope();
await using IDataUnitOfWork unitOfWork = new DataUnitOfWork(scope, sqlServiceAccessor);

A unit of work built over a scope you pass borrows it: disposing the unit of work leaves the scope to you. One built from a scope factory (new DataUnitOfWork(scopeFactory, sqlServiceAccessor), or DataUnitOfWorkFactory) owns its scope and disposes it. GetRepository<TEntity>() returns one repository per entity type, safe to call from racing threads; disposing the unit of work disposes every repository it handed out, then the scope it owns, even when one of them throws (a single failure is rethrown, several are thrown as an AggregateException).

IRequiresDataUnitOfWork marks a request (of Xpandables.Handlers) that runs inside a unit of work transaction: the pipeline behaviour of Xpandables.AspNetCore.Net commits it on success, and a failed result or an exception rolls it back.

Transient failures

A command run outside a transaction that fails transiently runs again: 3 retries from 100 ms, doubling, with jitter (ConfigureRetry). A read — the typed query APIs: queries, paged and compiled queries, counts, existence and scalar queries — runs again on every transient failure the dialect's IsTransient recognises: a deadlock, a serialization failure, a lost connection. A write — inserts, updates, deletes, upserts, procedures and raw SQL — runs again only on a failure that guarantees it had no effect (IsTransientWithoutEffect): a deadlock victim, a serialization failure, a busy database (SQL Server 1205, 3960, 40501, 40613; PostgreSQL 40001, 40P01, 57P03; MySQL 1213, 1205; Oracle ORA-00060, ORA-08177; SQLite busy or locked). After a lost connection (SQL Server 233, 64, 10053, 10054, 10060; PostgreSQL class 08; MySQL 2006, 2013; ORA-03113, ORA-03114) a write may already have run: it is not retried, and the provider's exception reaches the caller. A failure before the command is sent (opening the connection) runs any command again, a write included. A command whose parameter holds a value the provider reads once — a Stream, a TextReader, an XmlReader, a DbDataReader, a streamed table-valued parameter (IEnumerable<IDataRecord>) — is not retried. A reader runs again only before its first row. Several queries read at once (QueryAsync(queries)) are reads: sent in one DbBatch, the batch runs again on a transient failure raised before it returns its reader; where the provider has no batch, each query runs alone and is retried as a read. Inside a transaction — the scope's or an ambient TransactionScope — nothing is retried: the transaction is doomed. Run the whole unit again with ExecuteInTransactionAsync, which begins a transaction, runs the work, commits, and on a transient failure rolls back and runs it again in a new transaction:

Order order = await unitOfWork.ExecuteInTransactionAsync(request, async (request, token) =>
{
    Order created = Order.From(request);
    await orders.InsertAsync(created, token);
    await stock.UpdateAsync(…, token);
    return created;
}, IsolationLevel.Serializable, cancellationToken);

Inside a transaction already active — local or an ambient TransactionScope — ExecuteInTransactionAsync runs the work once in it. A transient failure while beginning a transaction (the reconnect refused) is retried as one of the work. A commit the database does not confirm is never run again (DataCommitOutcomeUnknownException). The delays wait on the container's TimeProvider when one is registered, and the token cancels them. The error codes are read from what the providers expose without a reference to them: SQL Server's HelpLink.EvtID, the SQLSTATE, MySqlConnector's Server Error Code, the ORA- and SQLite Error messages; derive from the dialect and override IsTransient, IsTransientWithoutEffect or GetErrorCode to change them.

Dependency Injection

AddXData registers a database in one call: its connections, a scoped connection scope shared by its unit of work and repositories, the SQL builder of its dialect, the repositories you add, its interceptors and telemetry.

using Microsoft.Extensions.DependencyInjection;

DbProviderFactories.RegisterFactory("Npgsql", NpgsqlFactory.Instance);

services.AddXData(data => data
    .UsePostgreSql(connectionString)
    .ConfigureSqlBuilder(options => options.NullSemantics = NullSemantics.CSharp)
    .AddRepository<Order>()
    .AddLogging());
DataBuilder method Purpose
UseDataSource(DbDataSource, SqlDialect) Connections from a data source you built (NpgsqlDataSource, …), not disposed by the library
UseSqlServer, UsePostgreSql, UseMySql, UseOracle, UseSqlite(connectionString) Connections from the registered provider
UseConnectionStringName(name) Connection string read from IConfiguration, with Provider=
UseSqlDialect(SqlDialectDefinition) Writes this database's SQL with a custom dialect definition (its Dialect must be the connection's)
ConfigureSqlBuilder(…) SQL builder options of this database
AddRepository<TEntity>(), AddRepository<TService, TImplementation>() Scoped repositories over this database's scope (a custom one receives the scope, the SQL service accessor and the interceptor chain its constructor asks for)
AddInterceptor<TInterceptor>(lifetime), AddLogging(…) Interceptors of this database, run in order (singleton unless a lifetime is passed)
ConfigureTelemetry(…) Telemetry options (RecordCommandText)

Exactly one Use… call is required; without one, or with a second, AddXData throws InvalidOperationException, as does a second AddXData for the same database (the default one, or one key): it would replace the database's services silently. Invalid ConfigureSqlBuilder options (a CollectionParameterThreshold or InClauseBatchSize not greater than zero) are rejected too. A UseSqlDialect definition whose Dialect is not the connection's throws InvalidOperationException when the database's services are resolved.

Startup check and health check

AddXData checks each database when the generic host starts: the connection factory is built and a connection created — not opened — so an unregistered provider or a malformed connection string stops the application at startup, with a message naming the database; every misconfigured database is reported. The generic host runs the check; a plain BuildServiceProvider() does not, unless you call IStartupValidator.Validate(). ValidateOnStart(false) turns it off. AddXDataHealthCheck() opens a connection and runs SELECT 1 (Oracle SELECT 1 FROM DUAL; a UseSqlDialect definition can override PingCommandText); its timeout and failureStatus are optional:

services.AddXData(data => data.UseSqlServer(connectionString));
services.AddXData("reporting", data => data.UsePostgreSql(reporting));
services.AddXDataHealthCheck();                                         // "data"
services.AddXDataHealthCheck("reporting-db", databaseKey: "reporting");

The individual AddXData* methods give finer control:

Method Registers
AddXDataConnectionMsSqlServer, AddXDataConnectionPostgreSql, AddXDataConnectionMySql, AddXDataConnectionOracle, AddXDataConnectionSQLite, AddXDataConnectionFactory The IDataConnectionFactory
AddXDataConnectionFactoryProvider(s), AddXDataConnectionScopeFactoryProvider Named connection factories / scope factories (GetFactory(name), GetScopeFactory(name))
AddXDataConnectionScopeFactory, AddXDataConnectionScope The scope factory and the scoped IDataConnectionScope
AddXDataMsSqlBuilder, AddXDataPostgreSqlBuilder, AddXDataMySqlBuilder, AddXDataSqlBuilder<TBuilder>, AddXDataSqlBuilderOptions The SQL builder and its options
AddXDataSqlMapper, AddXDataSqlServiceAccessor<T>, AddXDataSqlServiceAccessorFor, AddXDataSqlServiceAccessorFactory The mapper and the accessor pairing builder and mapper
AddXDataUnitOfWork, AddXDataUnitOfWork<T>, AddXDataUnitOfWorkKeyed<T> The scoped unit of work
AddXDataRepository<TEntity>, AddXDataRepository<TService, TImplementation>, AddXDataRepositoryKeyed<…>, AddXDataRepositories(lifetime, DataRepositoryRegistration.For<TService, TImplementation>()…) Repositories (scoped unless a lifetime is passed; a singleton is refused: a repository works on a scoped connection)
AddXDataCommandInterceptor(options), AddXDataCommandInterceptor<TInterceptor>(lifetime) Members of the interceptor chain

A method that names what it registers (a connection, a builder, a mapper, a repository, a unit of work, a scope factory delegate) replaces an earlier registration of the service, whatever the order; a default one (AddXDataSqlMapper(), AddXDataConnectionScopeFactory(), AddXDataConnectionScope(), AddXDataUnitOfWork(), AddXDataSqlServiceAccessorFactory()) registers only when none is, so AddXDataSqlServiceAccessorFor keeps your mapper; AddXDataRepositories registers only the interfaces not registered yet. A keyed repository or unit of work of your own type works on the database of its key (AddXData(key, …)), with that database's scope, SQL services and interceptor chain.

AddXDataUnitOfWork() resolves with only a connection factory and a SQL service accessor (or a SQL builder and mapper) beside it, and registers no interceptor. The repository overloads that take a scope factory (Func<IServiceProvider, IDataConnectionScope>) give their repository its own connection, outside the unit of work: DataRepository<TEntity> owns that scope and disposes it with itself, and a custom implementation must dispose it.

An assembly that declares repository classes (sealed class OrderRepository : DataRepository<Order>, IOrderRepository) gets a generated, internal services.AddXDataRepositoriesGenerated(lifetime) (scoped by default) that registers each sealed, non-generic one under its own type and forwards each of its repository interfaces to it (one instance per scope, however many interfaces it serves), unless one is already registered. [ExcludeFromRegistration] leaves a repository out.

Outside a container, DataUnitOfWorkFactory (IDataUnitOfWorkFactory.Create/CreateAsync) builds a unit of work that owns a new connection scope, from a scope factory, an IDataSqlServiceAccessorFactory and a provider invariant name. DataSqlBuilderFactory and DataSqlServiceAccessorFactory return the builder or accessor of a SqlDialect or a provider invariant name.

Connections

IDataConnectionFactory creates the provider's connections (CreateConnection/CreateConnectionAsync return them closed, CreateOpenConnection/CreateOpenConnectionAsync open them). An IDataConnectionScope wraps one connection, its dialect and its current transaction:

  • CreateScope()/CreateScopeAsync() give a scope whose connection opens on first use (EnsureOpenAsync), so no thread blocks while the connection is established; CreateOpenScope()/CreateOpenScopeAsync() open it at once.
  • The scope owns its connection and disposes it, rolling back a transaction still open.
  • A connection whose state is Broken is closed and reopened by EnsureOpen(Async).
  • DataBuilder.CommandTimeout(TimeSpan) sets one timeout for every command and batch of the database, including the scopes IDataConnectionScopeFactoryProvider creates for the connection named by UseConnectionStringName.
  • CreateCommand(SqlQueryResult) creates a command bound to the scope's transaction, with the statement's parameters.
  • Definition is the dialect definition the database is written with (the one of UseSqlDialect, otherwise the built-in one): SQL written by hand quotes and qualifies names with it to reach the tables the repositories use.

A scope gives the connection it opened back to the pool after each command run outside a transaction, and opens it again for the next command (DataConnectionRelease.AfterCommand, the default): a request that waits between commands holds no connection. A local transaction (BeginTransactionAsync) keeps the connection until it commits or rolls back, then gives it back; inside an ambient TransactionScope, it goes back at the end of the first command after the scope completes, or when the scope is disposed. ConnectionRelease(DataConnectionRelease.OnDispose) keeps it until the scope is disposed — needed for session state such as temporary tables. A connection handed to new DataConnectionScope(…) already open is never closed before disposal, nor is a private in-memory SQLite database's (Data Source=:memory:; file::memory: or a named file:notes?mode=memory, its cache not shared; or Mode=Memory without Cache=Shared) or a private temporary one (an empty or absent Data Source, deleted on close), which lives only with its connection (SqlDialectDefinition.KeepsConnectionOpen); a shared-cache one (cache=shared in the URI, or the Cache=Shared keyword) lives while any connection to it is open and is released as usual. With Npgsql and AfterCommand, an application that keeps no session state can add No Reset On Close=true to the connection string: otherwise the pool sends reset statements with the next open.

A scope runs one operation at a time: starting a query while another one's rows are still being read throws InvalidOperationException; read the first one to its end, or give each concurrent task its own scope. A reader opened on a command of scope.CreateCommand() is not an operation of the scope: while it is open run no repository command on that scope, or keep the connection with a transaction or OnDispose. A SQL Server connection string with MultipleActiveResultSets=True runs nested reads on one connection: the check is skipped, and the connection goes back to the pool when the last of them ends.

Multiple databases

Register each additional database under a key; every service it registers is keyed, so it never shares a scope, a SQL builder or interceptors with another database:

services.AddXData("reporting", data => data
    .UseSqlServer(reportingConnectionString)
    .AddRepository<SalesFigure>());

public sealed class SalesReport([FromKeyedServices("reporting")] IDataRepository<SalesFigure> figures) { }

Interceptors

An IDataCommandInterceptor (or a DataCommandInterceptor subclass, whose methods do nothing by default) is told about each command: CommandExecutingAsync before it runs, CommandExecutedAsync with its duration and affected rows (null for a reader), CommandFailedAsync with its duration and exception. The DataCommandContext carries the SQL text, the parameters, the DataCommandOperationType (Reader, Scalar, NonQuery) and the entity type name.

Every interceptor added — AddInterceptor<T>() on the builder, or AddXDataCommandInterceptor<T>() — runs in registration order, once per type, through a DataCommandInterceptorChain. An interceptor that throws is logged at Warning through ILogger<DataCommandInterceptorChain> (its type, the operation and the entity, never the SQL text or the parameter values; a cancellation at Debug) and skipped; the next one still runs, and the command's outcome never changes. Every interceptor registered directly as the IDataCommandInterceptor becomes a member of the chain. The chain is a singleton unless one of its members is scoped or transient (an audit interceptor reading the current user, say: AddXDataCommandInterceptor<AuditInterceptor>(ServiceLifetime.Scoped)): it is then built per scope, so no scope's member outlives it. No interceptor runs unless one is added.

AddLogging(…) on the builder, or AddXDataCommandInterceptor(options => …), adds DataLoggingCommandInterceptor, which logs through source-generated [LoggerMessage] methods:

Level When
Debug before execution (SQL text and parameter names) and after a success (duration, row count and SQL text)
Warning instead of the success line, after a success slower than SlowCommandThreshold
Error on failure: duration, SQL text, parameter names and exception

Parameter values appear only with EnableSensitiveDataLogging; a provider exception message is logged as the provider writes it, and some providers include values in it.

DataCommandInterceptorOptions Default Purpose
EnableSensitiveDataLogging false Log parameter values (@p0='Widget') as well as their names
CategoryName the interceptor's full type name Log category
SlowCommandThreshold null Duration above which a success is logged at Warning
services.AddXData(data => data
    .UseSqlServer(connectionString)
    .AddLogging(options => options.SlowCommandThreshold = TimeSpan.FromSeconds(2)));

The logging options are shared by every database.

Telemetry

Each command is one client span (ActivitySource Xpandables.Data) and one db.client.operation.duration point (seconds, Meter Xpandables.Data), with the OpenTelemetry database attributes: db.system.name, db.namespace (the database), db.operation.name, db.collection.name (the table), server.address, server.port, and on failure error.type and db.response.status_code (the database's error code). SQL Server's db.namespace is instance|database for a named instance. Only what the command states is reported: db.operation.name is the statement's first keyword (SELECT, INSERT, UPDATE, DELETE, MERGE, after whitespace and comments; none for another statement) or EXECUTE for a procedure (db.stored_procedure.name), and db.collection.name is set on the commands the repository builds from its records, never on SQL text or a procedure. The span is named "INSERT Orders", "DELETE" for SQL text, "EXECUTE dbo.Purge" for a procedure, and covers the opening of the connection. Each commit and rollback is a COMMIT / ROLLBACK span. Nothing is created unless something listens:

builder.Services.AddOpenTelemetry()
    .WithTracing(tracing => tracing.AddSource("Xpandables.Data"))
    .WithMetrics(metrics => metrics.AddMeter("Xpandables.Data"));

The SQL text (db.query.text) is recorded only with ConfigureTelemetry(options => options.RecordCommandText = true); parameter values never are.

Trimming and Native AOT

Xpandables.Data is trim- and AOT-safe by design: no public member requires unreferenced or dynamic code, and the library behaves the same whether or not the application is published with Native AOT. Records are read and written by generated code; a projection compiles its selector once per shape (interpreted under Native AOT); the builders translate expression trees without generating code, and DataQuery.For keeps the decimal operators a predicate such as p => p.Price > 15m needs; repository registrations and the compiled-query overloads are generated. The only warnings a trimmed application can see come from its own expression trees that build anonymous types or object initializers (see Data Records).

Main Types

  • DataRepository<TEntity>
  • DataUnitOfWork and DataUnitOfWorkFactory
  • DataConnectionFactory, DataConnectionScope and DataConnectionScopeFactory
  • DataTransaction
  • DataBuilder (AddXData)
  • IDataCommandInterceptor, DataCommandInterceptor, DataCommandInterceptorChain and DataLoggingCommandInterceptor
  • SqlDialectDefinition and the five dialect definitions (SqlServerDialect, PostgreSqlDialect, MySqlDialect, OracleDialect, SqliteDialect)
  • DataQuery, DataQuerySource, CompiledDataQuery<...> and DataQueryArgs<...>
  • DataUpdater<TEntity>
  • DataRecordAttribute, DataRecords, DataRecordMetadata<T> and DataRecordPlan
  • DataValueAttribute and DataValues
  • IDataSqlBuilder and the five dialect builders
  • DataSqlMapper
  • DataCommand, DataCommandResult and DataResultSets
  • SqlQueryResult and SqlParameter
  • SqlFunctions

License

Apache License 2.0. See LICENSE.

Product Compatible and additional computed target framework versions.
.NET net11.0 is compatible. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (4)

Showing the top 4 NuGet packages that depend on Xpandables.Data:

Package Downloads
Xpandables.Events

Event-driven architecture: in-process publish/subscribe, event-sourced aggregates and an event store, outbox and inbox with a hosted scheduler, over Xpandables.Data; Native AOT compatible.

Xpandables.Events.Data

Events ADO.NET implementation.

Xpandables.Results.Pipelines

Pipeline pattern implementation.

Xpandables.AspNetCore.Net

ASP.NET Core minimal API integration of the Xpandables libraries: Result to HTTP responses and problem details, endpoint filters, routes, request context, pipeline behaviors and DI extensions; Native AOT compatible.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
11.0.0 0 11/29/2026
10.0.2 209 3/15/2026
10.0.1 180 2/20/2026