From f1d622124bbeebf45c88739df1f365023bc7a719 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Efe=20=C4=B0nal?= <87021466+efeesrefinal@users.noreply.github.com> Date: Tue, 17 Nov 2026 16:21:03 +0300 Subject: [PATCH] Treat a JSON array element as nullable when setting a JSON property from it Fixes #4097 --- ...yableMethodTranslatingExpressionVisitor.cs | 2 ++ .../ComplexJsonBulkUpdateNpgsqlTest.cs | 29 +++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/src/EFCore.PG/Query/Internal/NpgsqlQueryableMethodTranslatingExpressionVisitor.cs b/src/EFCore.PG/Query/Internal/NpgsqlQueryableMethodTranslatingExpressionVisitor.cs index c75813978..242e3dadb 100644 --- a/src/EFCore.PG/Query/Internal/NpgsqlQueryableMethodTranslatingExpressionVisitor.cs +++ b/src/EFCore.PG/Query/Internal/NpgsqlQueryableMethodTranslatingExpressionVisitor.cs @@ -1525,6 +1525,8 @@ private static bool MayReturnNull(SqlExpression expression) SqlParameterExpression { IsNullable: true } => true, ColumnExpression { IsNullable: true } => true, JsonScalarExpression { IsNullable: true } => true, + // An array index that is out of range yields NULL, whatever the nullability of the element + JsonScalarExpression { Path: var path } when path.Any(s => s.ArrayIndex is not null) => true, PgJsonTraversalExpression => true, SqlFunctionExpression { IsNullable: true } => true, diff --git a/test/EFCore.PG.FunctionalTests/Query/Associations/ComplexJson/ComplexJsonBulkUpdateNpgsqlTest.cs b/test/EFCore.PG.FunctionalTests/Query/Associations/ComplexJson/ComplexJsonBulkUpdateNpgsqlTest.cs index ddc050ae2..3a34ccefc 100644 --- a/test/EFCore.PG.FunctionalTests/Query/Associations/ComplexJson/ComplexJsonBulkUpdateNpgsqlTest.cs +++ b/test/EFCore.PG.FunctionalTests/Query/Associations/ComplexJson/ComplexJsonBulkUpdateNpgsqlTest.cs @@ -352,6 +352,35 @@ WHERE jsonb_array_length(r."RequiredAssociate" -> 'Ints') >= 2 """); } + [ConditionalFact] + public virtual async Task Update_property_to_out_of_range_primitive_collection_element() + { + await TestHelpers.ExecuteWithStrategyInTransactionAsync( + Fixture.CreateContext, + Fixture.UseTransaction, + async context => + { + await context.Set() + .ExecuteUpdateAsync(s => s.SetProperty(x => x.RequiredAssociate.Int, x => x.RequiredAssociate.Ints[10])); + + // The property becomes a JSON null and the rest of the document is kept + using (Fixture.ListLoggerFactory.SuspendRecordingEvents()) + { + Assert.Equal( + 0, + await context.Database.SqlQueryRaw( + """SELECT count(*)::int AS "Value" FROM "RootEntity" WHERE "RequiredAssociate" -> 'Int' IS DISTINCT FROM 'null'::jsonb""") + .SingleAsync()); + } + }); + + AssertSql( + """ +UPDATE "RootEntity" AS r +SET "RequiredAssociate" = jsonb_set_lax(r."RequiredAssociate", '{Int}', r."RequiredAssociate" #> '{Ints,10}') +"""); + } + #endregion Update primitive collection #region Multiple updates