efcore
efcore copied to clipboard
Query: logic protecting SUM from returning null doesn't work for complex scenarios
query:
from c in cs
select new
{
Sum = c.Orders.Sum(o => o.OrderID) + 1
}
throws: Nullable object must have a value.
query plan:
(QueryContext queryContext) => IAsyncEnumerable<<>f__AnonymousType225<int>> _InterceptExceptions(
|__ source: IAsyncEnumerable<<>f__AnonymousType225<int>> _ShapedQuery(
| |__ queryContext: queryContext,
| |__ shaperCommandContext: SelectExpression:
| | SELECT (
| | SELECT SUM([o].[OrderID])
| | FROM [Orders] AS [o]
| | WHERE [c].[CustomerID] = [o].[CustomerID]
| | ) + 1 AS [Sum]
| | FROM [Customers] AS [c],
| |__ shaper: (QueryContext queryContext | ValueBuffer c) => new { (int)Nullable<int> TryReadValue(c, 0, null) }),
|__ contextType: TestModels.Northwind.NorthwindRelationalContext,
|__ logger: DiagnosticsLogger<Query>,
|__ queryContext: Unhandled parameter: queryContext)
instead we should generate coalesce 0 as well:
(QueryContext queryContext) => IAsyncEnumerable<<>f__AnonymousType225<int>> _InterceptExceptions(
|__ source: IAsyncEnumerable<<>f__AnonymousType225<int>> _ShapedQuery(
| |__ queryContext: queryContext,
| |__ shaperCommandContext: SelectExpression:
| | SELECT (
| | SELECT SUM([o].[OrderID])
| | FROM [Orders] AS [o]
| | WHERE [c].[CustomerID] = [o].[CustomerID]
| | ) + 1 AS [Sum]
| | FROM [Customers] AS [c],
| |__ shaper: (QueryContext queryContext | ValueBuffer c) => new { (int)Nullable<int> TryReadValue(c, 0, null) ?? default(int) }),
|__ contextType: TestModels.Northwind.NorthwindRelationalContext,
|__ logger: DiagnosticsLogger<Query>,
|__ queryContext: Unhandled parameter: queryContext)
As a workaround, I've just used c.Orders.Any() ? c.Orders.Sum(o => o.OrderID) : 0. This translates, albeit adding extra fluff.
@maumar - Coalesce like that on client side wouldn't work. The result with coalesce would be 0 in this case but l2o result would be 1.
bringing back to triage, since we had a customer report and it does produce incorrect result
Identify SqlFunction of Sum in null semantics and coalesce 0.