Skip to content

Commit 39c0ef8

Browse files
authored
Fix First warning detection for outer null checks (#39735)
Part of #39310
1 parent ea50b18 commit 39c0ef8

2 files changed

Lines changed: 19 additions & 1 deletion

File tree

‎src/EFCore.Relational/Query/RelationalQueryableMethodTranslatingExpressionVisitor.cs‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2793,9 +2793,13 @@ private static bool IsFilteredOnlyByForeignKeyCorrelation(SelectExpression selec
27932793
}
27942794

27952795
var keyComparisons = new List<(ColumnExpression Outer, ColumnExpression Inner)>();
2796+
var nullChecks = new List<ColumnExpression>();
27962797
if (!IsCorrelation(selectExpression.Predicate!)
27972798
|| keyComparisons.Count == 0
2798-
|| keyComparisons[0].Inner.Column is not IColumn { Table: var dependentTable })
2799+
|| keyComparisons[0].Inner.Column is not IColumn { Table: var dependentTable }
2800+
// A null check is only a navigation-generated guard if it is on one of the compared principal key columns.
2801+
// Any other one, e.g. c.City != null, is a user filter.
2802+
|| nullChecks.Any(n => !keyComparisons.Any(c => c.Outer.TableAlias == n.TableAlias && c.Outer.Name == n.Name)))
27992803
{
28002804
return false;
28012805
}
@@ -2816,6 +2820,7 @@ bool IsCorrelation(SqlExpression predicate)
28162820
{
28172821
OperatorType: ExpressionType.NotEqual, Left: ColumnExpression column, Right: SqlConstantExpression { Value: null }
28182822
}:
2823+
nullChecks.Add(column);
28192824
return IsOuter(column);
28202825

28212826
case SqlBinaryExpression

‎test/EFCore.Relational.Specification.Tests/Query/WarningsTestBase.cs‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,19 @@ public virtual void FirstOrDefault_without_orderby_doesnt_issue_warning_subquery
166166
Assert.DoesNotContain(Fixture.ListLoggerFactory.Log, l => l.Id == CoreEventId.FirstWithoutOrderByAndFilterWarning);
167167
}
168168

169+
[Fact]
170+
public virtual void FirstOrDefault_without_orderby_but_with_unrelated_outer_null_check_doesnt_issue_warning_subquery()
171+
{
172+
using var context = CreateContext();
173+
var query = context.Customers
174+
.OrderBy(c => c.CustomerID)
175+
.Select(c => c.Orders.FirstOrDefault(o => c.City != null)!.OrderDate)
176+
.ToList();
177+
Assert.Equal(91, query.Count);
178+
179+
Assert.DoesNotContain(Fixture.ListLoggerFactory.Log, l => l.Id == CoreEventId.FirstWithoutOrderByAndFilterWarning);
180+
}
181+
169182
[Fact]
170183
public virtual void FirstOrDefault_without_orderby_doesnt_issue_warning_subquery_correlated_by_computed_column()
171184
{

0 commit comments

Comments
 (0)