Efcore: Translation error using negative

Created on 8 Nov 2018  路  7Comments  路  Source: dotnet/efcore

Trying to sum a list of numbers and apply a negative value to it.
Seems like a translation issue?

Steps to reproduce

Summing up a list of rows in a transaction table
Basically I needed the negative value of a sum, it turns out it was actually giving me -180 instead of -220
Instead I did -1 * (1 * 200 + 20) and it gave the right result not sure why?

```c#
_db.Transactions.Select(x=> x.Type == MyEnum.Type1 ? -(price * units + bonus) : 0)
_db.Transactions.Select(x=> x.Type == MyEnum.Type1 ? -(1 * 200 + 20) : 0)

**Using a linq sample gives the correct values**
```c#
static void Main(string[] args)
        {
            var i = -(1 * 200 + 20);

            Console.WriteLine($"{i}");
        }

Further technical details

EF Core version: 2.1.4
Database Provider: Microsoft.EntityFrameworkCore.SqlServer
Operating system: Windows 10
IDE: Visual Studio 2017 15.8.9

area-query closed-fixed customer-reported good first issue poachable punted-for-3.0 type-bug

Most helpful comment

@smitpatel I would like to contribute to the EF Core project and believe this issue is a suitable entry point. I took a look and was able to verify that this issue still exists for SQL Server and SQLite. Is it currently up for grabs?

All 7 comments

@smitpatel @maumar it looks like in DefaultQuerySqlGenerator, VisitUnary visits ExpressionType.Negate by appending the hyphen and then visiting the operand. Probably needs to add parenthesis before and after visiting the operand.

For what it鈥檚 worth, the in-memory database does not have this problem (which is why my own attempts to reproduce this failed 馃槄)

@poke @tuespetre Actually I just realised that I'm using Z.EntityFramework.Plus Future query feature which might have the issue. I have opened up an issue there in case it's their issue more than entity framework?

var transactionQuery = _context.Transactions.AsNoTracking().Where(x => x.Id == id)
                .DeferredSum(
                    x => x.TradeType == TradeType.Buy ? -(x.Units * x.Stock.StockPrice.Last + x.Brokerage) : x.TradeType == TradeType.Sell ? x.Units * x.Stock.StockPrice.Last - x.Brokerage : 0)
                .FutureValue<decimal>();

No, I was able to reproduce the problem eventually with the SQLite provider.

@poke Ahh that's awesome news, cheers hopefully the EF team will get on top of this. Could be pretty critical for some apps

Probably this still exist in new pipeline. Also look for other operatorType in SqlUnary.

@smitpatel I would like to contribute to the EF Core project and believe this issue is a suitable entry point. I took a look and was able to verify that this issue still exists for SQL Server and SQLite. Is it currently up for grabs?

Was this page helpful?
0 / 5 - 0 ratings