Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

GateNonEntityOnNullabilityMarker also produces Expression.Default(objectType) for value-type MemberInit projections, which is a zeroed struct rather than null. This condition classifies every DefaultExpression as a null target, so a left-joined mutable struct/record-struct DTO such as default(AggStruct).Count is rewritten to a nullable SQL NULL instead of the LINQ DefaultIfEmpty value 0; the new reference-type DTO test does not cover this path. Restrict the DefaultExpression case to reference types (as the existing marker checks do) and add a value-type projection regression test.


// 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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<Context39714>(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<Context39714>(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<Part> Parts => Set<Part>();
public DbSet<Record> Records => Set<Record>();

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<Task> query)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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));

Expand Down
Loading