Release notes
Version 11 is 11.0.0-rc.14. For moving a 10.x codebase, read Coming from earlier versions first; this page lists each release.
Version 11 release candidates
Changes since rc.13
- A NULL into a non-nullable member is an error. It used to leave the member at its initializer or default. A NULL into
int Likesorstring Titlenow throwsValueMappingExceptionnaming the model and the 0-based row; a nullable member (int?,string?) getsnull. The typed read has no NULL check, so the rule costs nothing per cell. The same holds for a single value (Map<int>()) andExecuteScalarAsync<int>(). ExecuteScalarAsync<T>()andExecuteScalar<T>()throwValueMappingExceptionwhen the query returns no rows andTcannot holdnull. They used to returndefault. A nullable or referenceTstill getsnull: for a fallback, ask forint?and write(await command.ExecuteScalarAsync<int?>()) ?? -1.- New:
[NullPolicy]and[NullValue]say otherwise, on the model type or on one member.NullAction.Throwchecks and names the member, the column and the row;NullAction.Defaultkeeps the initializer (a constructor parameter's declared default);NullAction.Noneis no check.[NullValue(0)]replaces a NULL with a constant. Each check costs one NULL test per covered member per row; a model without them reads at full speed. See the NULL rules. - Renamed, with no
[Obsolete]step:ToAsyncBufferisToPooledBuffer,ToAsyncBufferStreamisToPooledBufferStream, andToBufferedAsyncStreamisToPooledStream. They behave as before; a call to an old name no longer compiles.Streamkeeps its name. - New:
StreamBuffered(stallTimeout, cancellationToken), and an overload that takes abufferSize, on every typed view andIMappedQuery<T>. The read runs up to 1,024 rows ahead of your loop (bufferSizesets it; it counts rows, not bytes), so a loop that does slow or async work per row does not hold the read back on every row. A stall is measured once the buffer is full. A size of 0 reads asStreamdoes; a negative size throwsArgumentOutOfRangeException. A customIMappedQuery<T>implements both overloads. See the three ways to read rows as they arrive. - A
DbQueryprocedure whose parameter names the provider does not report is asked again only after a short while, as a command does; it used to ask on every run. AddParamIf(false, value)adds nothing and does not look at the argument. It used to throwArgumentExceptionwhen no parameter name could be derived from the argument, even when the condition was false.- Docs. The guide's statements were checked against the code, and each mismatch found is fixed.
Changes since rc.12
The migration guide lists each removal with what to call instead.
- One way per job: the second ways are removed, with no
[Obsolete]step. The command shortcut terminalsToListAsync<T>,ToArrayAsync<T>,ToImmutableArrayAsync<T>,ToHashSetAsync<T>,FirstAsync<T>,FirstOrDefaultAsync<T>,SingleAsync<T>andSingleOrDefaultAsync<T>on a command are gone: callcommand.Map<T>().ToListAsync(cancellationToken)and its siblings.AsAsyncEnumerable(n, params others)is gone: pass[n, ..others]to theIEnumerable<int>overloads.GetMatchingOrdinalsis gone:MatchingOrdinals(names, sort).ToArray().ConnectionFactoryToPoolAdapteris internal:AsPool()returnsIDbConnectionPool(orIDbConnectionPool<TConnection>). - Channel and Dataflow are rebuilt over
Map<T>()and are published with the final 11.0.0, not in a release candidate. Their extensions on readers, commands andIExecuteReaderare removed: callMap<T>()first, thenToChannelReader,ToChannel,ToTargetBlockorAsSourceBlock. Channel no longer depends onOpen.ChannelExtensions. - Classic command parameters. A command built with
Command(...)on a literal text sizes its parameter list from the@namesthe text declares, and sends an input parameter written without its@(or in another case) under the text's own spelling, as aDbQuerydoes. An output, input-output or return-value parameter keeps the name it was added with, soParameters["id"]reads it back. Two spellings of one declared name are sent as written. - The raw reader's
ToListAsync(Func<IDataRecord, ValueTask<T>>)collects into pooled chunks and copies once into a list of exactly the number of rows, as the mapped terminals do, instead of growing a list. - Docs. New pages: a controller with no service layer, and the same with minimal APIs. The XML documentation of Core and MSSqlClient says what a caller needs and what a streaming member costs; every docsite page, README and sample is cut to what a reader needs, and the README performance figures come from the recorded data.
Changes since rc.11
The migration guide groups the removals by theme, with what to call instead.
- Everything marked
[Obsolete]is removed, with theResultsfamily and the per-row command terminals that duplicate aMapterminal.Results<T>,ResultsAsync<T>,ResultsBuffered<T>,ResultsFromDataTable,DataTable.To<T>, the selector forms ofFirst,FirstOrDefault,Single,SingleOrDefault,Take,Skip,SkipThenTake,ToList,ToArrayandToImmutableArray,ExpressiveDbCommandBase.TakeAsync,IterateReader*,ForEachAsyncon commands,QueryResultCollection<T>,DequeueAs<T>, the token-firstReadAsync, thebool configureAwaitoverloads ofEnsureOpenAsyncandOpenAsync, and the protectedExpressiveCommandBase.Concat<T>are gone. CallMap<T>().ToListAsync(cancellationToken)orMap(selector)with the terminal you need; add.SingleResult()beforeMapwhere the old call read only the first result set. Behavior a caller will notice:ResultsandResultsAsyncwere lazy andToListbuffers every row; an emptyDataTabledoes not report a missingrequiredcolumn (table.Map(map).ToList()reports at the first row);Take(0)runs the command. - Rows without a model:
AsObjectArrays()andAsDictionaryRows(). They are mapped views likeMap<T>()(the same terminals,SkipandTake,SingleResult(),AsyncReads(),UsePool, read-through and pooling) onIExecuteReader,IDbCommand,IDataReader,DataTableand theDbQuerydefinition.DictionaryRowis areadonly structover oneobject?[]and the column names that every row of the result set shares;row["Id"]matches the exact name, else ignoring case, androw.ToDictionary()copies. A database NULL isnull. They replaceRetrieve,RetrieveAsync,QueryResult<T>,QueryResultQueue<T>,DequeueAs<T>,DequeueAsMappedDictionaries,AsMappedDictionaries,FirstOrdinalResultsandFirstOrdinalResultsAsync,AsEnumerable(IDataReader, ...),GetValues(IDataRecord, ...)andGetValuesFromOrdinals, which are removed with no[Obsolete]step. Core.Transformer<T>is removed: map withMap<T>(), or aRowMap<T>passed toMap. The mapped overloads of the Channel and Dataflow packages rent their row arrays fromArrayPool<object>.Sharedand clear them on return.- The blocking calls are in
Open.Database.Extensions.Synchronous. Addusing Open.Database.Extensions.Synchronous;where the compiler says a blocking call is missing (CS1061, CS1929). Nothing a blocking call does changes.Execute<T>(f)andExecuteReader<T>(f)inferT, so a call that namedTalone needs both type arguments or none. A command type of your own has no blocking side: a blocking call throwsNotSupportedExceptionand the message says to use the async call. TheExecuteTransaction*overloads that took the token right after the connection are removed: pass it after the callback. Stream(stallTimeout, cancellationToken)is the one unbuffered read. It is onMappedQuery<T>,MappedQueryWithSkip<T>,MappedQueryWithTake<T>andMappedCommand<T>and returns anIAsyncEnumerable<T>: lazy, enumerated once. The timeout is required: the longest the consumer may go without pulling the next row. A stalled consumer stops the read, cancels the command, closes the connection the library opened and gets aTimeoutExceptionon its next pull;Timeout.InfiniteTimeSpanaccepts an unbounded hold. It replacesRead,Read<TResult>,ReadAsyncandReadAsync<TResult>on those four views.IMappedQuery<T>has two members,ToAsyncBufferStreamandStream; its extension terminals are gone (call the terminal on the view), and theIExecuteReaderSync,IExecuteCommandSyncandIMappedQuerySync<T>interfaces are not public.MappedReader<T>andMappedTable<T>keep their ownReadandReadAsync.- The cancellation token can be passed positionally. Every terminal with an optional comparer, command behavior or flag has an overload that ends in
CancellationToken cancellationToken = default:await query.ToDictionaryAsync(post => post.Id, cancellationToken). The comparer or behavior on the original member is required (source-level only; compiled callers are unaffected). A baredefaultin that slot binds the token overload:reader.ForEachAsync(handler, default)reads withReadAsync, where it bound the flag (false, synchronous reads) before. Passfalseto keep synchronous reads. DbQuerytakesMap<T>()on the definition.DbQuery.Text(sql).Map<Post>()(alsoMap(RowMap<T>)andMap(selector), and the same onDbQuery<TParams>) is an immutableMappedDbQuery<T>: the map and its compiled reader live with the definition.Using(connection | transaction | pool | factory)returns the mapped view, and parameters go before or afterUsingwith the same command either way.PooledBuffer<T>.From(rows)makes a finished buffer from rows you already have. A read that finds no rows completesItemswith the sharedPooledArray<T>.Empty, which keeps working after the buffer is disposed.- Decorated models are hard instructions.
[Column(Name)],[Column(Order = n)]and[NotMapped]on a model are honored by the runtime map: a declared column that is missing, or not at its declared ordinal, throwsValueMappingException(checked once per result set, nothing per row); a declared name matches exactly or ignoring case, never by inference;[NotMapped]members are never read; contradictions throwInvalidOperationExceptionat the call; aRowMap<T>pair on a member overrides its declarations. - The pool hand-off is by bytes. A released chunk is cleared by the recycle bin from 128 KB of rows (rows times row size), value rows included; a smaller one is cleared in place.
- Null arguments are refused with
ArgumentNullException, thrown at the call, forIDbConnection.OpenAsync,AsPool, theFuncconnection-sourceCommandandStoredProcedureextensions,ReadAsyncand theDataRecordordinal helpers. A connection that reportedOpen | Brokenis closed again after a transaction call, and the transactionCreateCommandextensions dispose the command if the provider refuses the transaction. DbQueryCallis areadonly struct.DbQueryCall?isNullable<DbQueryCall>, so== nullno longer compiles. A parameter name written by hand that the SQL text declares (with or without@, any case) is sent as the text writes it (@name); an undeclared name is sent as written; procedures are unchanged.Open.Database.Extensions.SqlClient(System.Data.SqlClient) is not published for version 11. UseOpen.Database.Extensions.MSSqlClient(Microsoft.Data.SqlClient). The Channel and Dataflow packages are published with the final 11.0.0.- Docs and benchmarks. The XML documentation of Core and MSSqlClient is rewritten; the
DictionaryRowremarks say which reads allocate nothing; the pooling page has the bin proof; the library comparison is a newer run; the two LocalDB benchmark classes are gone and the SQL Server benchmark databases keep their files in the scratch folder.
Changes since rc.10
- A query can be defined once and bound where it runs:
DbQuery.DbQuery.Text(sql)andDbQuery.Procedure(name)make an immutable definition (a static field is the natural home);Using(connection | transaction | pool | factory)binds it to wherever it runs, and eachAddParamreturns a new immutable call.Params<T>()declares a struct of values the compiler checks. Parameter names are resolved as a command resolves them. The connection is opened late and closed only when the call opened it (closed or broken); a factory's connection is disposed and a pool's is given back even when the run throws; a transaction's connection is never opened or closed. See Expressive commands. - Pooled arrays follow one clearing rule. Rows that hold references are always cleared before their array goes back to the pool; nothing turns that off. Rows without references are cleared only when you ask: per query with
clearOnReturn: true, or for the whole app with the switchOpen.Database.Extensions.ClearPooledArrays. Only the rows that were written are cleared, and a chunk of 128 KB or more of rows is cleared off the read path. See Async buffers and streams. - New:
.UsePool(ArrayPool<T> pool, bool clearOnReturn)afterMapchooses the pool and the clearing for one query; both arguments are required, and every pooling terminal (ToListAsync,ToArrayAsync,ToImmutableArrayAsync,ToHashSetAsync,ToDictionaryAsync, the buffers and streams) rents from it. An explicitclearOnReturn: falsewins over the app-wide switch for that query, except for reference rows. Used through theIMappedQuery<T>interface it is honoured the same way; a query that is not ODX's own is collected without pooling. - Removed: the flag and pool overloads of
ToAsyncBuffer,ToAsyncBufferStreamandToBufferedAsyncStream(clearOnDispose/clearOnReturnandMemoryPool<T>). Each now takes only a cancellation token:query.UsePool(pool, clearOnReturn: true).ToAsyncBuffer(cancellationToken)replacesquery.ToAsyncBuffer(pool, true, cancellationToken). - New:
ConnectionScope<TConnection>, withEnsureOpenScopeandEnsureOpenScopeAsyncon a connection, a connection factory and a connection pool. The scope opens the connection if it needs it and, when disposed, lets go of it the way its source calls for: a connection you already hold is closed again if the scope opened it (never disposed), a factory's connection is disposed, a pool's is given back.await using var _ = await connection.EnsureOpenScopeAsync(cancellationToken);replaces the open-and-closetry/finally;scope.Connectionandscope.PriorStategive the connection and the state it was found in, andscope.ReaderBehavior()addsCommandBehavior.CloseConnectionwhen the scope opened the connection. TheOpen,OpenAsync,UsingandUsingAsynccallbacks of a factory or a pool are built on it, so the asynchronous factory callbacks now dispose withDisposeAsync. - A broken connection is closed again afterwards, and one that is not a
DbConnectionis not leaked. The checks that decide whether a command closes a connection it opened share one definition (closed, connecting or broken). ADbQueryfactory or pool that supplies something that is not aDbConnectionhas it disposed or given back, and the run throwsInvalidOperationExceptionnaming the type. - Docs. The benchmarks pages: one per exploration and one shared page for the method.
Changes since rc.9
ToListAsync,ToArrayAsync,ToImmutableArrayAsync,ToHashSetAsyncandToDictionaryAsyncbuild an exactly sized result, once. A list or array used to grow while the reader was open (doubling, so a 10,000-row list kept room for 16,384). The rows now go into a chain of pooled chunks on the calling flow, with no background producer, and the result is built right after the last row: one block copy for a list, an array or an immutable array, and a hash set or dictionary created at the size of the result, so it never regrows.ToImmutableArrayAsyncwraps the array without a copy on .NET 8 and later. The synchronousToHashSetandToDictionarywork the same way. In the library's synthetic benchmark, 10,000 rows intoToListAsynctake 206 µs, against 522 µs in rc.9; with a 50 µs network link every route is within 3%, so expect less time on the CPU and less garbage, not a faster query. Bytes per call against SQL Server LocalDB are at most 16 B above rc.9 for 1 and 100 rows, and 1,320 B below it for a 100-row list. One change you can see: a duplicate or null key inToDictionaryandToDictionaryAsyncthrows the same exception as before, but only after every row has been read, and the key and value selectors run after the read. New:PooledArray<T>.ToArray()andToList()copy a buffer's rows into an exactly sized array or list.Derived parameter names allocate no more than explicit ones when the SQL text is built at run time, and nothing is stored for such a text. The
@namemarkers of a text command were remembered per string object, so a text assembled on every call was parsed again on every call and left an entry behind: 680 B more per call for one parameter, 1,360 B for four. Now only a literal orconsttext (an interned string) is parsed once and remembered. Any other text is matched by a scan that allocates nothing and stores nothing, so a rebuilt text costs within 16 B of naming the parameters yourself. The price is CPU time: the scan runs on every call, and it grows with the length of the text and the number of parameters. In a single-threaded benchmark it took about 0.5 µs for a 200-character text with one parameter and about 20 µs for a 2,000-character text with four. Astatic readonlytext that is built at startup is not interned either, so it is scanned on every call too. Where that matters, keep the SQL in a literal orconst, or name the parameters. No API changes.An unreadable procedure is looked up once in 15 seconds, not once per run, and a stale list no longer outlives an empty answer. When the provider reported no parameter names for a stored procedure (the login cannot see it, it does not exist, or it declares no parameters), nothing was remembered, so every run read the names again: one extra schema query per execute while the connection was open. And when such an answer came after an older list, the older list stayed for the full five minutes, so a procedure that had lost its parameters was still sent the old ones. An empty answer now replaces the older list and is remembered for 15 seconds (a fraction of the five minutes for known names, so a procedure that is created or changed shows up soon). Derived names are sent as written until then. No API changes.
A parameter added to a stored procedure is no longer silently left out of an
AddParamscall.AddParams(new { Id, Title })against a procedure that declared only@Idremembered those names, and when the procedure later gained@Title(inside the five minutes the names are remembered), the run droppedTitlewith no error and the procedure used its default. A member that the remembered names do not declare now makes the library read the names once more before it drops the member, as an unmatchedAddParam(value)argument already did. If the second read still lacks the member it is dropped as before, and that read is remembered, so a member the procedure never takes costs one extra read per five minutes, not one per run (a procedure that declares no parameters: every 15 seconds, see above). No signatures change. See Remembered names.A mapped read no longer boxes a date, a decimal or a bool that the provider hands over as another type. SQLite stores a date and a decimal as text and a bool as an integer, so the column type differs from the member type, and each such cell cost a box on top of the value: 24 bytes for a
DateTime, 32 for adecimal, 48 for abool, per row (the nullable members too). The map now reads them through a typed conversion with the same culture, the same failures and the same NULL rules as before, and allocates what the hand-written read does. No signatures change.Docs. A "Start here" at the top of the what-is-new page. New articles: Shaping rows and How little code (the same four tasks with ODX, Dapper, EF Core and ADO.NET). The streaming members are documented as not the recommended way to read rows, because they hold the connection for every row. Async buffers and streams covers who owns a
PooledBufferand for how long, including returning one from a controller. Mapping shows how to get an immutable or frozen result from the terminals.
Changes since rc.8
- A NULL passed to a typed
AddParamoverload is now sent with that type.AddParam("@id", (long?)null),AddParam("@x", default(int?))andAddParam("@s", (string?)null)(and the same forms ofAddParamIf) used to send the NULL with no database type, so the provider chose its own default. A consumer reported that as a different parameter type, an implicit conversion and a different query plan on SQL Server. The parameter now takes the database type of the overload's static type, the same mappingAddParamsalready used for a NULL member. A database type you pass always wins, and a value is left to the provider as before. Two things to know: a bareAddParam("@a", null)literal binds thestring?overload, so it is now sent as aStringNULL; and a value of typeobject, or a call that gives the direction by position (AddParam(name, value, ParameterDirection.Input)), has no type to use, so pass a database type or writedirection: .... No signatures change.
Changes since rc.7
- New:
ToAsyncBuffer,ToAsyncBufferStreamandToBufferedAsyncStreamon the typed views (whatMap<T>()returns, withSkipandTake). Each reads the query on its own background producer into pooled chunks, so the connection is released as soon as the last row is read, however slowly the consumer works.ToAsyncBufferstarts the read at the call and returns aPooledBuffer<T>that you can hand to another layer (a controller, say) and read later:await buffer.Itemsgives aPooledArray<T>, a read-only list with an O(1) indexer that LINQ copies quickly. Disposing the buffer returns the arrays to the pool, and cancels the query if it is still running.ToAsyncBufferStreamis a lazy, single-useIAsyncEnumerable<ReadOnlyMemory<T>>of chunks, andToBufferedAsyncStreamis the same stream element by element. Each took aclearOnDisposeorclearOnReturnflag and optionally aMemoryPool<T>; in rc.11 they take only a cancellation token, and the pool and the clearing are chosen once with.UsePool(ArrayPool<T> pool, bool clearOnReturn)afterMap(see "Changes since rc.10"). Rows that hold references are always cleared before their array goes back; rows without references only when you ask. See Async buffers and streams. - Clearing a large chunk is done off the read path, and bounded. (Changed in rc.12: see "Changes since rc.11".) A chunk of rows that hold references and is 4,096 rows or more is cleared on one background loop; a smaller one is cleared where it is released. If the loop cannot take a chunk (it is behind, or it throws), the chunk is cleared where it is released instead: nothing is skipped, left dirty or lost. See Pooled memory.
- Removed:
ToChannelReaderandToChannelon the typed views (whatMap<T>()returns, withSkipandTake): 48 signatures in all. A call to one no longer compiles. They are planned to come back in the Channel library. To read a query while a consumer works, useToBufferedAsyncStream(the elements) orToAsyncBufferStream(the chunks): the query is read on a background producer and the connection is released as soon as the last row is read. For a projection after the map, useSystem.Linq.Asyncover the stream. The row count thatToChannel(out Task<long> readCount, ...)returned has no replacement: count the rows as you read them, or readItems.Countof a buffer. See Channels and Dataflow. TheToChanneloverloads of the Channel library, on a command or a reader, are not affected.
Changes since rc.6
- A cancel that cuts a reader-level read short now throws
OperationCanceledException.ForEach,IterateWhile,SelectandSelectAsyncon a reader, their async forms, and the reader-levelToChanneloverloads that take a transform used to end quietly by default and return a partial result that looked complete. They now check the token at the top of the loop, before each read, and the async forms hand it toReadAsyncandNextResultAsync, so the provider cancels the read itself. A read that already returned its last row is complete: a cancel after that is not an error. Removed: thethrowOnCancellationparameter onForEach,IterateWhile,SelectandSelectAsync, six signatures in all. A call that passed it no longer compiles (CS1503 or CS1501): delete the argument, as inSelect(reader, transform, cancellationToken). To stop early without an exception, returnfalsefrom the predicate or leave the loop. A mapped query over a plainIDataReadernow forwards the token, so a cancel between rows throws. AddParamandAddParamIftake anobject?value in the(name, value, type, direction)forms, so a typed NULL such asAddParam(name, (byte[]?)null, SqlDbType.VarBinary)compiles without a nullability warning and sendsDBNull. No existing call changes.- A stored procedure's parameter names are resolved on every run. A command that gets its names from the database (
AddParam(value)with no name) used to resolve them once and write them intoParams, so a second run of the same command object, after a change of connection, database or procedure, could send the first run's names. The names are now resolved on every run into a list of their own, andParamskeeps what you added. No API changes. One visible change: after a run,Paramsshows what you added, not the resolved names. To see what was sent, read the provider command'sParametersinExecute(command => ...). - Documentation: a new AsyncReads() page says why rows are read with
Read()by default, what the opt-in costs and when to use it. The Performance page now leads with ranked charts, with their data tables and CSVs in Performance data, and the same charts are on a benchmark charts page. The Core README has a section on trimming and native AOT, with a recipe for a trimmed app (see "Known limitations"). The examples in the README, the mapping article, the samples and the XML documentation use async terminals with a realCancellationToken,staticlambdas and one pair per line.
Changes since rc.5
Rows are read with
Read()by default, on async terminals too.ToListAsync,FirstOrDefaultAsyncand the other async terminals still execute the command and open the connection asynchronously, but they read the rows withRead(). On the measured runs a synchronous row read costs less CPU, and about 40% less memory on theMap(Func)path, for the same wall time over a real network link. To read the rows withReadAsync(), for a caller whose thread must not block while rows arrive, callAsyncReads():cmd.AsyncReads().Map<T>(), ordbCommand.Map<T>().AsyncReads(). Removed, with no bridge:EnableAsyncRead(bool)and theUseAsyncReadproperty. ReplaceEnableAsyncRead()withAsyncReads(). A plainIDataReaderread by an async terminal now checks the cancellation token on every row.RowMap<T>.From(factory, pairs)builds a map from a delegate, such as a lambda, a method group or a constructor wrapper. Its parameters bind to columns by the rules a constructor already uses: a pair renames a parameter to a column, then columns match by name, ignoring case. A missing orNULLvalue in a non-nullable parameter gets the parameter's declared default, elsedefault. Declare the map once:static readonly RowMap<PostSummary> Summary = RowMap<PostSummary>.From( static (int id, string title) => new PostSummary(id, title)); List<PostSummary> posts = await cmd .Map(Summary) .ToListAsync(cancellationToken);On C# 12 the pairs argument must be written out. A single target-typed
new(...)as the only pair does not compile: write the element type.The
Map<T>(pair...)overloads are removed. There is one way to pass pairs: aRowMap<T>, declared once and passed toMap. A one-off isMap(new RowMap<T>(pair, pair)).Map<T>([...]), with a collection expression, still compiles: it converts to aRowMap<T>. One behavior change comes with it, with no compile error:Map<int>([])now throws (see Coming from earlier versions).Select(selector)on anIMappedQuery<T>, added in rc.5, is removed: it built a second object for every row while the reader was open. Shape each row into the result type withMap(RowMap<TResult>.From(factory))instead. A data class can return that mapped query and let each caller choose the terminal. The reader-levelSelectis unchanged.Fix: the async terminals on an
IMappedQuery<T>that this library did not build (your own implementation) no longer resume on the caller's synchronization context.Fix: an
AddParamsmember that the procedure, or the command text, does not declare is no longer sent under a stale name left in a shared pool.A package built in a Release build no longer carries the build machine's folder names: the SDK's
DeterministicSourcePathsmaps the repository folder to a neutral prefix in the dll, the debug symbols and the Source Link mapping.
Changes since rc.4
- Version 11 targets .NET 11: every package adds
net11.0next tonet10.0(LTS),netstandard2.0andnetstandard2.1(MSSqlClient:net472,net10.0andnet11.0). Each major version of the library targets the matching .NET. Building the repository needs the .NET 11 SDK (global.json). .SingleResult()can be written beforeMap, so a query reads as behavior first, then shape:command.SingleResult().Map<Post>().ToListAsync(cancellationToken). It works on an expressive command (IExecuteReader) and on a rawIDbCommandorDbCommand, with the sameMapoverloads as before, and it is the same ascommand.Map<Post>().SingleResult(), which still works. There is none onIDataReaderorDataTable: their views never read through, so there is nothing to opt out of. Nothing changes by default: without it aMapterminal still reads through the later result sets.ExecuteScalar<T>()andExecuteScalarAsync<T>()convert the wayMap<T>()does. They cast the provider's value exactly, so abigintread asint, or anumericread aslong, threwInvalidCastException, which a port from Dapper met only on a real database. Now a value that is already aTis returned as it is, an integer converts to another integer type with a range check, and any other value is converted by the same codeMap<T>()uses.NULLand no row still givedefault(T). A value that cannot be converted, or does not fit, throwsValueMappingExceptionwith the conversion's error inside. Behavior change: a call that threwInvalidCastExceptionnow converts, or throws that exception.ExecuteReturn<T>()andExecuteReturnAsync<T>()convert the same way. The overloads that take aFunc<object?, T>are unchanged.- A
RowMap<T>takes a converter for a column that needs a trim, a parse or a format on its way to a member:map.Convert<long, string>(nameof(Order.OrderNum), n => n.ToString("D6")), orConvert<TColumn, TMember>(member, column, convert)to name the column as well. It returns a new map, and the delegate runs inside the compiled row reader, so a result maps straight into the type you want, with no row type to copy from. A converter is not called for a NULL cell (the member follows the NULL rules); aNullable<>TColumnis called with null. See Converting a column. First()andSingle()(andFirstAsync(cancellationToken),SingleAsync(cancellationToken)) onMap<T>()throwInvalidOperationExceptionwhen the query returns no row, andSinglealso when it returns more than one. An insert that returns its new id is oneawait command.Map<long>().SingleAsync(cancellationToken), with no handler to check the row count. The commands have the shortcuts too:command.SingleAsync<long>(cancellationToken). ANULLvalue is still a row. The error for no rows is thrown after the connection is released and the later result sets are read, so a failure in one of them comes first. See Terminals.ToDictionaryandToDictionaryAsynconMap<T>()take a value selector:ToDictionaryAsync(post => post.Id, post => post.Body ?? "")builds the lookup in one pass, without keeping the rows. A duplicate key throws, as it does without the value selector.
Breaking in rc.4
Rebuild consumers of rc.3. Both changes are source-compatible for every call except the ones noted.
ExpressiveDbCommand.RetrieveAsynctakes a trailingCancellationToken cancellationToken = defaulton the three overloads that can:RetrieveAsync(CancellationToken),RetrieveAsync(IEnumerable<int>, CancellationToken)andRetrieveAsync(IEnumerable<string>, bool, CancellationToken). The token is used together with the command's own token. Aparamslist must come last, so the twoparamsoverloads (RetrieveAsync(int, params IEnumerable<int>)andRetrieveAsync(string, params IEnumerable<string>)) are unchanged and take no token: pass the ordinals or names as a collection to theIEnumerableoverload to cancel. A call that passed no token binds to the same overload as before, but the signatures are new, so rebuild.- Three parameters are renamed to say what they hold. This breaks only a caller that passes the argument by name:
CreateTextCommand(SqlTransaction, ...)inSqlClientandMSSqlClienttakescommandText(it wasprocedureName),CreateStoredProcedureCommand(IDbConnection, ...)in Core takesprocedureName(it wascommandText), and the type parameterTConnof theUsingandUsingAsyncconnection helpers is nowTConnection. The type-parameter rename breaks no caller.
Changes since rc.3
- The asynchronous terminals on a command take the element type:
await command.ToArrayAsync<int>(cancellationToken)isMap<int>()then the terminal.Map<T>()of a single value such asintreads the first column. reader.Map<T>()andcommand.Map<T>()map a plainIDataReaderorIDbCommandwith the same terminals as an expressive command'sMap<T>(). The reader is never opened, closed, disposed or advanced to the next result set; a command opens and closes only the connection it opened. See Mapping a reader or a command you already have.table.Map<T>()maps a DataTable you already have (aMappedTable<T>; each terminal reads through its own DataTableReader).- A null
RowMap<T>passed toMap<T>(map)no longer throwsArgumentNullException: it maps exactly asMap<T>()does (a single value reads the first column). - A type of your own that implements both
IExecuteReaderandIDbCommand(orIDataReader) now gets an ambiguousMapcall (CS0121); cast it to the interface you mean. - A
defaultMappedQuery<T>(orMappedQueryWithSkip<T>,MappedQueryWithTake<T>) now throwsInvalidOperationExceptionwhen used, where it threwNullReferenceException. - Members with a better route are marked
[Obsolete]. Each message names the replacement, and they are removed in rc.12. They are warnings, never errors, but a build that treats warnings as errors stops on them until you move to the replacement or suppressCS0618. - The asynchronous command paths dispose their reader with
ConfigureAwait(false)onnetstandard2.1,net10.0andnet11.0. - The
Map<T>documentation now says how columns match by default: exactly, else ignoring case, else ignoring case and underscores (author_idfeedsAuthorId).
Changes since rc.2
- A
Mapterminal now reads through the later result sets after the first, so a failure in a later statement is thrown, where rc.2 returned the rows and lost it. This is a behavior change from rc.2.Mapstill returns only the first set's rows..SingleResult()afterMapstops after the first set and does not see a later failure. A later failure can follow a write that already committed, so a caller that retries can repeat it. The older command methods, Channel and Dataflow do not read through yet. ToDataTablenow reads one result set and leaves the reader on it, soNextResultworks after it. A secondToDataTablecall in a row returns no rows, because the reader is still on that set and its rows are already read. A loop onwhile (!reader.IsClosed)aroundToDataTableno longer ends: useNextResult.ToDataTablesreturns one table per result set.- A connection the library opened is closed when the provider fails to start a reader, in Core and in the two SQL Server packages.
EnsureOpenAsyncandOpenAsyncalways useConfigureAwait(false). The overloads with abool configureAwaitare obsolete and ignore it (removed in rc.12).- A null collection is treated as empty, and a null reader or selector is checked once.
Changes since rc.1
- Generic commands (
ExpressiveCommand,ExpressiveDbCommand) send each parameter's direction, so output parameters work. AddParam(name, DbType, direction)works on the SQL Server commands.AddParams(x)withxtypedobjectsends the members of its real type.AddParam(value)finds a stored procedure's parameter names through theProcedureParametersschema on anyDbConnection.- On a text command,
AddParam(value)andAddParams(object)use the@namemarkers in the SQL. Map<T>()on a dictionary orExpandoObjectthrows, where it used to return empty rows.
Fixes in 11.0, since 10.1.0
ExecuteReturn<T>()andExecuteReturnAsync<T>()returndefault(T)for a NULL return value instead of throwingNullReferenceExceptionfor a value type.- Channels and Dataflow. With
complete: false, the command no longer runs twice. The mappedToChannel<T>,ToChannelAsync<T>andToTargetBlock<T>overloads complete your target only after every row has been delivered and the reader released (before, up to about 1,024 buffered rows could be lost with a bounded target). They no longer lose the last row when the reader fails mid-stream, and they map correctly when the reader has extra unmapped columns. - Connections and commands.
OpenAsync(IDbConnection)no longer opens aDbConnectiontwice.EnsureOpenAsynccloses a connection that finished opening just as cancellation arrived.FirstOrdinalResults<T>(IDbCommand, behavior)honorsbehavior. - The synchronization context. The async transaction helpers and the
ExecuteReaderAsyncoverloads of the two SQL Server packages no longer resume on the caller's synchronization context: they await withConfigureAwait(false), and so does the connection open they trigger. A caller that blocked on one from a thread with a synchronization context no longer waits on that context inside the library. - A parameter with no value is now sent by both SQL Server packages. It was never added to the command, so an output parameter (
AddParam(name, direction)) never reached SQL Server. SQL Server needs a type and size for an output parameter and refuses the command without them. AddParam("name", someString)swapped the name and the value on a compiler older than C# 13 (the .NET 8 SDK). It was found in11.0.0-preview05and fixed in11.0.0-preview06:AddParam(string, string?)andAddParamIf(bool, string, string?)use the name you write on every compiler.AddParam(name, value, dbType)compiles again. In the 11.0 previews a call that gave a value and a database type, such asAddParam("@id", id, SqlDbType.Int), failed with an ambiguous-call error (CS0121) for anint,long,short,byteorstringvalue (theintforms compiled in 10.1.0). New overloads with a required database type, onAddParamandAddParamIf, make every such call bind to one overload; no existing member changed.- A
charis sent as the character again. In the 11.0 previews,AddParam("x", 'c')bound to theintoverload and sent the number 99; 10.1.0 sent the character. It does again.
Earlier versions
10.1.0
A modernization and allocation-reduction pass. Source-compatible with 10.0: existing code recompiles cleanly.
Target frameworks.
net10.0is the primary, modern target.netstandard2.0andnetstandard2.1are retained as shimmed legacy paths (.NET 8 and .NET 9 consumers use thenetstandard2.1build).Open.Database.Extensions.MSSqlClientalso targetsnet472. The explicitnet8.0andnet9.0targets were dropped.Fewer allocations on the hot paths. Case-insensitive column-to-property matching uses
StringComparer.OrdinalIgnoreCase(andFrozenDictionaryonnet10.0) instead of allocating an upper-cased string per column. Assorted per-query LINQ and dead code were removed.Ergonomic field-mapping overrides.
Results<T>,ResultsAsync<T>,To<T>and similar methods accept target-typednew(...)and collection expressions:cmd.Results<Person>(new("FirstName", "first_name"), new("LastName", "last_name")); cmd.Results<Person>([new("FirstName", "first_name"), new("LastName", "last_name")]);In 11,
Results<T>andResultsAsync<T>are removed: see Coming from earlier versions.Modernized
params. Ordinal helpers (Retrieve,AsEnumerableand others) acceptparams IEnumerable<int>andparams IEnumerable<string>: any enumerable, not just arrays.Read-only inputs. Several read-only
IList<T>parameters were widened toIReadOnlyList<T>(GetValuesFromOrdinals,EnumerateValuesFromOrdinals,ToDictionary). Arrays,List<T>,ImmutableArray<T>and similar types still bind. A custom type that implements onlyIList<T>, and not alsoIReadOnlyList<T>, would need to recompile; no BCL collection is affected.Lower per-query overhead.
Transformer<T>caches its per-type reflection once instead of rebuilding it on every query. Buffered and data-table paths pre-size collections and avoid redundantSelectiterators.Fixed a wasted-allocation and incorrect-return bug in
CopyToDBNullAsNull.The public API surface is tracked with
Microsoft.CodeAnalysis.PublicApiAnalyzers, and unit-test coverage was substantially expanded.
9.0
- The
Open.Database.Extensionsmeta-package is discontinued. - .NET 9.0 was added to the targets so that compilation and performance improvements are available.
- Some .NET 8 and .NET 9 specific features were implemented.
- Significant cleanup and simplification where possible.
8.0
- All
.ConfigureAwait(true)became.ConfigureAwait(false), as they should be. A caller that needs to resume on the calling context must.ConfigureAwait(true)itself. - Added
Open.Database.Extensions.MSSqlClientforMicrosoft.Data.SqlClientsupport. - .NET 8.0 was added to the targets so that compilation and performance improvements are available.
- Improved nullable integrity.