diff --git a/src/EFCore.Relational/Query/RelationalSqlTranslatingExpressionVisitor.cs b/src/EFCore.Relational/Query/RelationalSqlTranslatingExpressionVisitor.cs index bd6f8341e45..9cbc998fcda 100644 --- a/src/EFCore.Relational/Query/RelationalSqlTranslatingExpressionVisitor.cs +++ b/src/EFCore.Relational/Query/RelationalSqlTranslatingExpressionVisitor.cs @@ -647,16 +647,41 @@ protected override Expression VisitMember(MemberExpression memberExpression) { // Fold member access into conditional, i.e. transform // (test ? expr1 : expr2).Member -> (test ? expr1.Member : expr2.Member) + // When either branch is null (e.g. a non-entity outer-join projection gated on its nullability marker), + // propagate SQL NULL instead of creating an untranslatable member access on null. case ConditionalExpression conditional: - return Visit( - Expression.Condition( - conditional.Test, - Expression.MakeMemberAccess(conditional.IfTrue, member), - Expression.MakeMemberAccess(conditional.IfFalse, member))); + { + var ifTrue = MakeMemberAccess(conditional.IfTrue, member, memberExpression.Type); + var ifFalse = MakeMemberAccess(conditional.IfFalse, member, memberExpression.Type); + if (ifTrue.Type != ifFalse.Type) + { + var nullableType = memberExpression.Type.MakeNullable(); + if (ifTrue.Type != nullableType) + { + ifTrue = Expression.Convert(ifTrue, nullableType); + } + + if (ifFalse.Type != nullableType) + { + ifFalse = Expression.Convert(ifFalse, nullableType); + } + } + + return Visit(Expression.Condition(conditional.Test, ifTrue, ifFalse)); + + static Expression MakeMemberAccess(Expression target, MemberInfo member, Type memberType) + => !target.Type.IsValueType && target is ConstantExpression { Value: null } or DefaultExpression + ? Expression.Constant(null, memberType.MakeNullable()) + : Expression.MakeMemberAccess(target, member); + } // Reduce member accesses on new expressions (new { A = 8 }.Select(x => x.A) => 8) case NewExpression @new when @new.Members?.IndexOf(member) is int index && index >= 0: return Visit(@new.Arguments[index]); + + case MemberInitExpression memberInit + when memberInit.Bindings.SingleOrDefault(mb => mb.Member.IsSameAs(member)) is MemberAssignment memberAssignment: + return Visit(memberAssignment.Expression); } var inner = Visit(memberExpression.Expression); diff --git a/test/EFCore.Relational.Specification.Tests/BulkUpdates/NonSharedModelBulkUpdatesRelationalTestBase.cs b/test/EFCore.Relational.Specification.Tests/BulkUpdates/NonSharedModelBulkUpdatesRelationalTestBase.cs index 2fd97dd0374..271993aa553 100644 --- a/test/EFCore.Relational.Specification.Tests/BulkUpdates/NonSharedModelBulkUpdatesRelationalTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/BulkUpdates/NonSharedModelBulkUpdatesRelationalTestBase.cs @@ -171,6 +171,129 @@ public class ComplexThing } } + [Theory, MemberData(nameof(IsAsyncData))] // #39714 + public virtual async Task Update_with_left_join_to_group_by_projection(bool async) + { + var contextFactory = await InitializeNonSharedTest(seed: async context => await context.Seed()); + + await TestHelpers.ExecuteWithStrategyInTransactionAsync( + contextFactory.CreateDbContext, + UseTransaction, + async context => + { + var aggQ = from r in context.Records + group r by r.PartId into g + select new + { + PartId = g.Key, + NormalHours = (decimal?)g.Sum(r => r.Hours), + Count = g.Count() + }; + + var query = from pe in context.Parts + join a in aggQ on pe.Id equals a.PartId into ljg + from lj in ljg.DefaultIfEmpty() + select new { Part = pe, Agg = lj }; + + var rowsAffected = async + ? await query.ExecuteUpdateAsync(u => u + .SetProperty(x => x.Part.NormalHours, x => x.Agg.NormalHours.GetValueOrDefault())) + : query.ExecuteUpdate(u => u + .SetProperty(x => x.Part.NormalHours, x => x.Agg.NormalHours.GetValueOrDefault())); + + Assert.Equal(2, rowsAffected); + + var parts = await context.Parts.AsNoTracking().OrderBy(p => p.Id).ToListAsync(); + Assert.Equal(2, parts.Count); + Assert.Equal(15m, parts[0].NormalHours); + Assert.Equal(0m, parts[1].NormalHours); + }); + } + + [Theory, MemberData(nameof(IsAsyncData))] // #39714 + public virtual async Task Update_with_left_join_to_group_by_dto_projection(bool async) + { + var contextFactory = await InitializeNonSharedTest(seed: async context => await context.Seed()); + + await TestHelpers.ExecuteWithStrategyInTransactionAsync( + contextFactory.CreateDbContext, + UseTransaction, + async context => + { + var aggQ = from r in context.Records + group r by r.PartId into g + select new Context39714.AggDto + { + PartId = g.Key, + NormalHours = (decimal?)g.Sum(r => r.Hours), + Count = g.Count() + }; + + var query = from pe in context.Parts + join a in aggQ on pe.Id equals a.PartId into ljg + from lj in ljg.DefaultIfEmpty() + select new { Part = pe, Agg = lj }; + + var rowsAffected = async + ? await query.ExecuteUpdateAsync(u => u + .SetProperty(x => x.Part.RecordCount, x => (int?)x.Agg.Count)) + : query.ExecuteUpdate(u => u + .SetProperty(x => x.Part.RecordCount, x => (int?)x.Agg.Count)); + + Assert.Equal(2, rowsAffected); + + var parts = await context.Parts.AsNoTracking().OrderBy(p => p.Id).ToListAsync(); + Assert.Equal(2, parts.Count); + Assert.Equal(2, parts[0].RecordCount); + Assert.Null(parts[1].RecordCount); + }); + } + + protected class Context39714(DbContextOptions options) : DbContext(options) + { + public DbSet Parts => Set(); + public DbSet Records => Set(); + + public async Task Seed() + { + Parts.AddRange( + new Part { Id = 1, NormalHours = 99m, RecordCount = 99 }, + new Part { Id = 2, NormalHours = 99m, RecordCount = 99 }); + Records.AddRange( + new Record { Id = 1, PartId = 1, Hours = 10m }, + new Record { Id = 2, PartId = 1, Hours = 5m }); + await SaveChangesAsync(); + } + + public class Part + { + [DatabaseGenerated(DatabaseGeneratedOption.None)] + public int Id { get; set; } + + [Precision(18, 2)] + public decimal NormalHours { get; set; } + public int? RecordCount { get; set; } + } + + public class Record + { + [DatabaseGenerated(DatabaseGeneratedOption.None)] + public int Id { get; set; } + + public int PartId { get; set; } + + [Precision(18, 2)] + public decimal Hours { get; set; } + } + + public class AggDto + { + public int PartId { get; set; } + public decimal? NormalHours { get; set; } + public int Count { get; set; } + } + } + #region HelperMethods protected static async Task AssertTranslationFailedWithDetails(string details, Func query) diff --git a/test/EFCore.SqlServer.FunctionalTests/BulkUpdates/NonSharedModelBulkUpdatesSqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/BulkUpdates/NonSharedModelBulkUpdatesSqlServerTest.cs index e284686fcb7..1d1f02de7f9 100644 --- a/test/EFCore.SqlServer.FunctionalTests/BulkUpdates/NonSharedModelBulkUpdatesSqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/BulkUpdates/NonSharedModelBulkUpdatesSqlServerTest.cs @@ -321,6 +321,60 @@ FROM [Blogs] AS [b] """); } + public override async Task Update_with_left_join_to_group_by_projection(bool async) + { + await base.Update_with_left_join_to_group_by_projection(async); + + AssertSql( + """ +SET NOCOUNT OFF; +UPDATE [p] +SET [p].[NormalHours] = ISNULL(CASE + WHEN [r0].[marker] IS NULL THEN NULL + ELSE [r0].[NormalHours] +END, 0.0) +FROM [Parts] AS [p] +LEFT JOIN ( + SELECT [r].[PartId], ISNULL(SUM([r].[Hours]), 0.0) AS [NormalHours], 1 AS [marker] + FROM [Records] AS [r] + GROUP BY [r].[PartId] +) AS [r0] ON [p].[Id] = [r0].[PartId] +""", + // + """ +SELECT [p].[Id], [p].[NormalHours], [p].[RecordCount] +FROM [Parts] AS [p] +ORDER BY [p].[Id] +"""); + } + + public override async Task Update_with_left_join_to_group_by_dto_projection(bool async) + { + await base.Update_with_left_join_to_group_by_dto_projection(async); + + AssertSql( + """ +SET NOCOUNT OFF; +UPDATE [p] +SET [p].[RecordCount] = CASE + WHEN [r0].[marker] IS NULL THEN NULL + ELSE [r0].[Count] +END +FROM [Parts] AS [p] +LEFT JOIN ( + SELECT [r].[PartId], COUNT(*) AS [Count], 1 AS [marker] + FROM [Records] AS [r] + GROUP BY [r].[PartId] +) AS [r0] ON [p].[Id] = [r0].[PartId] +""", + // + """ +SELECT [p].[Id], [p].[NormalHours], [p].[RecordCount] +FROM [Parts] AS [p] +ORDER BY [p].[Id] +"""); + } + private void AssertSql(params string[] expected) => TestSqlLoggerFactory.AssertBaseline(expected); diff --git a/test/EFCore.Sqlite.FunctionalTests/BulkUpdates/NonSharedModelBulkUpdatesSqliteTest.cs b/test/EFCore.Sqlite.FunctionalTests/BulkUpdates/NonSharedModelBulkUpdatesSqliteTest.cs index 2b6efaf406f..7952dd7b8f2 100644 --- a/test/EFCore.Sqlite.FunctionalTests/BulkUpdates/NonSharedModelBulkUpdatesSqliteTest.cs +++ b/test/EFCore.Sqlite.FunctionalTests/BulkUpdates/NonSharedModelBulkUpdatesSqliteTest.cs @@ -292,6 +292,66 @@ public override async Task Update_complex_type_property_with_view_mapping(bool a """); } + public override async Task Update_with_left_join_to_group_by_projection(bool async) + { + await base.Update_with_left_join_to_group_by_projection(async); + + AssertSql( + """ +UPDATE "Parts" AS "p0" +SET "NormalHours" = COALESCE(CASE + WHEN "s"."marker" IS NULL THEN NULL + ELSE "s"."NormalHours0" +END, '0.0') +FROM ( + SELECT "p"."Id", "r0"."NormalHours" AS "NormalHours0", "r0"."marker" + FROM "Parts" AS "p" + LEFT JOIN ( + SELECT "r"."PartId", COALESCE(ef_sum("r"."Hours"), '0.0') AS "NormalHours", 1 AS "marker" + FROM "Records" AS "r" + GROUP BY "r"."PartId" + ) AS "r0" ON "p"."Id" = "r0"."PartId" +) AS "s" +WHERE "p0"."Id" = "s"."Id" +""", + // + """ +SELECT "p"."Id", "p"."NormalHours", "p"."RecordCount" +FROM "Parts" AS "p" +ORDER BY "p"."Id" +"""); + } + + public override async Task Update_with_left_join_to_group_by_dto_projection(bool async) + { + await base.Update_with_left_join_to_group_by_dto_projection(async); + + AssertSql( + """ +UPDATE "Parts" AS "p0" +SET "RecordCount" = CASE + WHEN "s"."marker" IS NULL THEN NULL + ELSE "s"."Count" +END +FROM ( + SELECT "p"."Id", "r0"."Count", "r0"."marker" + FROM "Parts" AS "p" + LEFT JOIN ( + SELECT "r"."PartId", COUNT(*) AS "Count", 1 AS "marker" + FROM "Records" AS "r" + GROUP BY "r"."PartId" + ) AS "r0" ON "p"."Id" = "r0"."PartId" +) AS "s" +WHERE "p0"."Id" = "s"."Id" +""", + // + """ +SELECT "p"."Id", "p"."NormalHours", "p"."RecordCount" +FROM "Parts" AS "p" +ORDER BY "p"."Id" +"""); + } + protected override DbContextOptionsBuilder AddNonSharedOptions(DbContextOptionsBuilder builder) => base.AddNonSharedOptions(builder).ConfigureWarnings(wcb => wcb.Log(SqliteEventId.CompositeKeyWithValueGeneration));