efcore icon indicating copy to clipboard operation
efcore copied to clipboard

Query: logic protecting SUM from returning null doesn't work for complex scenarios

Open maumar opened this issue 8 years ago • 4 comments

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)

maumar avatar Jul 13 '18 00:07 maumar

As a workaround, I've just used c.Orders.Any() ? c.Orders.Sum(o => o.OrderID) : 0. This translates, albeit adding extra fluff.

bmarder avatar Oct 18 '18 15:10 bmarder

@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.

smitpatel avatar Oct 18 '18 18:10 smitpatel

bringing back to triage, since we had a customer report and it does produce incorrect result

maumar avatar Mar 03 '20 21:03 maumar

Identify SqlFunction of Sum in null semantics and coalesce 0.

smitpatel avatar Jun 01 '20 17:06 smitpatel