You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Change DateTime JSON serialization to fixed width - #39131
I've posted a comment on an issue with a detailed description of how I am planning to contribute and got approval from a member of the team
The code builds and tests pass locally (also verified by our automated build checks)
Commit messages follow this format:
Summary of the changes
- Detail 1
- Detail 2
Fixes #bugnumber
Tests for the changes have been added (for bug fixes / features)
Code follows the same patterns and style as existing code in this repo
Summary
JsonDateTimeReaderWriter used to write DateTime values with trailing zero fractional seconds omitted (e.g. 2026-01-01T00:00:00Z vs 2026-01-01T00:00:00.1200000Z). Because the string length varies, string comparison (e.g. ORDER BY in Cosmos) doesn't match chronological order. Values are now written in a fixed-width ISO 8601 format with seven fractional digits: yyyy-MM-dd'T'HH:mm:ss.fffffffK.
Changes
JsonDateTimeReaderWriter writes the fixed-width format by default. A new public constructor JsonDateTimeReaderWriter(string format) lets the format be customized; "yyyy-MM-dd'T'HH:mm:ss.FFFFFFFK" restores the previous behavior. ConstructorExpression handles both the singleton and custom instances (for compiled models).
SQL Server datetime/smalldatetime: these types can't convert strings with more than three fractional digits (CAST('2020-01-05T12:30:45.0000000' AS datetime) fails with Msg 241 / 295), which broke JSON queries such as OPENJSON ... WITH ([value] datetime '$'). SqlServerDateTimeTypeMapping therefore uses a reader/writer with three fractional digits (yyyy-MM-dd'T'HH:mm:ss.fffK) for those store types. datetime2 and date keep the seven-digit default.
Baselines: updated the affected SQL Server, Cosmos and specification test baselines for the new format.
Existing data in the old format
Reading is unchanged (Utf8JsonReader.GetDateTime() accepts both formats), so documents written by previous versions are still materialized correctly. Note, however, that ordering and range comparisons on the server compare strings, so they can still be wrong between old short-format values and new fixed-width values until existing documents are rewritten (for example by loading and saving them, or by a one-off update script).
Tests
JsonDateTimeReaderWriterTest: default fixed-width output, custom format matching the previous Utf8JsonWriter output, round-tripping (value and Kind), and ConstructorExpression.
AdHocMiscellaneousQueryCosmosTest.DateTime_in_legacy_short_format_is_read_correctly: inserts a document with a short-format DateTime directly through the Cosmos SDK and asserts it materializes correctly in entity instances, scalar projections and anonymous-type projections.
AdHocMiscellaneousQueryCosmosTest.DateTime_with_and_without_fractional_seconds_orders_and_filters_correctly: ordering and filtering on values with and without fractional seconds.
- Fall back to Cosmos SDK serialization when parameter values do not match the mapping type
- Preserve default SDK handling for parameter values incompatible with configured type mappings
Fixesdotnet#39113
This regression test only inserts documents through the new writer, so it does not verify that legacy documents containing the short form (for example, "2026-01-01T00:00:00Z") remain readable. The provider-independent JSON expectations were changed away from that form, leaving the compatibility claim from the review thread uncovered. Seed one document as raw legacy JSON (the existing AdHocCosmosTestHelpers.CreateCustomEntityHelperAsync supports this) and assert it materializes correctly.
🧠 Review effort: Balanced
Give feedback about Copilot approvals in this survey to enter a drawing for a $150 gift card.
…net#39113)
- Seed a document with a short-format DateTime through the SDK and verify it
materializes correctly in entity instances and in projections
- Update remaining DateTime expectations missed by the fixed-width change
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Add a public JsonDateTimeReaderWriter constructor that takes the format used
when writing values, so the previous behavior can be restored with
"yyyy-MM-dd'T'HH:mm:ss.FFFFFFFK".
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…otnet#39113)
datetime and smalldatetime cannot be converted from strings with more than
three fractional second digits, so use a fixed-width millisecond format for
them. Update the affected SQL Server baselines.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ement mapping
- Serialize elements of List<object>/object[] parameters through the element
type mapping when all elements match it, so DateTimes use the same fixed-width
format as stored values
- Fall back to SDK serialization when any element doesn't match
- Add tests for List<object> and object[] Contains over DateTime
Part of dotnet#39113
- Create FromSql parameters via CosmosTypeMapping.CreateParameter so DateTime
values match the fixed-width format of stored values
- Keep SqlValueParameter for null values and types without a mapping
- Add tests for FromSqlRaw and interpolated FromSql with a DateTime parameter
Part of dotnet#39113
JsonCollectionOfReferencesReaderWriter reports ValueType == typeof(object), so this check accepts mixed object-backed collections without validating their elements. A captured List<object> { "ALFKI", 1 } used in values.Contains(c.CustomerID) then throws InvalidCastException in the string reader/writer instead of serializing the mixed array as before. Route incompatible reference collections through the elementwise/fallback path too, and add a regression with mixed contents.
Preserve mapped serialization for null-containing date collections
A captured List<object?> { timestamp, null } or object?[] used in dates.Contains(x.Timestamp) falls back to SDK serialization for the entire collection here. The exact-second DateTime then uses the old short format and silently misses a freshly saved fixed-width value. Write null elements with WriteNullValue() while retaining mapped serialization for non-null elements, and add null-containing variants of the collection regressions.
CSharpMigrationsGeneratorTest.SeedData_annotations_are_stored_in_snapshot and NorthwindSelectQueryCosmosTest.Select_anonymous_non_numeric_constants need to be updated to use the new format
…ql parameter serialization (dotnet#39113)
- Use model-level type mappings for FromSql parameters and constants
- Serialize object-backed collections per element, writing nulls directly and falling back only for incompatible elements
- Route collections of references through element compatibility checking
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
I'm not sure though about the error propagating from the npm modules, I hadn't changed anything in that regards, it could be the test environment itself.
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
Human assessment is needed because critical DateTime serialization mismatches across parameter paths can cause equality queries to miss newly saved documents.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
JsonDateTimeReaderWriterused to writeDateTimevalues with trailing zero fractional seconds omitted (e.g.2026-01-01T00:00:00Zvs2026-01-01T00:00:00.1200000Z). Because the string length varies, string comparison (e.g.ORDER BYin Cosmos) doesn't match chronological order. Values are now written in a fixed-width ISO 8601 format with seven fractional digits:yyyy-MM-dd'T'HH:mm:ss.fffffffK.Changes
JsonDateTimeReaderWriterwrites the fixed-width format by default. A new public constructorJsonDateTimeReaderWriter(string format)lets the format be customized;"yyyy-MM-dd'T'HH:mm:ss.FFFFFFFK"restores the previous behavior.ConstructorExpressionhandles both the singleton and custom instances (for compiled models).datetime/smalldatetime: these types can't convert strings with more than three fractional digits (CAST('2020-01-05T12:30:45.0000000' AS datetime)fails with Msg 241 / 295), which broke JSON queries such asOPENJSON ... WITH ([value] datetime '$').SqlServerDateTimeTypeMappingtherefore uses a reader/writer with three fractional digits (yyyy-MM-dd'T'HH:mm:ss.fffK) for those store types.datetime2anddatekeep the seven-digit default.Existing data in the old format
Reading is unchanged (
Utf8JsonReader.GetDateTime()accepts both formats), so documents written by previous versions are still materialized correctly. Note, however, that ordering and range comparisons on the server compare strings, so they can still be wrong between old short-format values and new fixed-width values until existing documents are rewritten (for example by loading and saving them, or by a one-off update script).Tests
JsonDateTimeReaderWriterTest: default fixed-width output, custom format matching the previousUtf8JsonWriteroutput, round-tripping (value andKind), andConstructorExpression.AdHocMiscellaneousQueryCosmosTest.DateTime_in_legacy_short_format_is_read_correctly: inserts a document with a short-formatDateTimedirectly through the Cosmos SDK and asserts it materializes correctly in entity instances, scalar projections and anonymous-type projections.AdHocMiscellaneousQueryCosmosTest.DateTime_with_and_without_fractional_seconds_orders_and_filters_correctly: ordering and filtering on values with and without fractional seconds.Fixes #39113