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