Skip to content

Incorrect SQL for cast inside an aggregate (MS SQL) #2029

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
AlekseyMartynov opened this issue Feb 28, 2019 · 2 comments · Fixed by #2036
Closed

Incorrect SQL for cast inside an aggregate (MS SQL) #2029

AlekseyMartynov opened this issue Feb 28, 2019 · 2 comments · Fixed by #2036

Comments

@AlekseyMartynov
Copy link

Version: 5.2.3 from NuGet

Code to reproduce:

session.Save(new TestClass { Int32Prop = Int32.MaxValue });
session.Save(new TestClass { Int32Prop = Int32.MaxValue });

session.Query<TestClass>()
    .GroupBy(i => 1)
    .Select(g => new {
        s = g.Sum(i => (long)i.Int32Prop)
    })
    .ToArray();

Generated SQL

select cast(sum(testclass0_.Int32Prop) as BIGINT) as col_0_0_ from TestClass testclass0_

fails with

Arithmetic overflow error converting expression to data type int.

Looks like sum and cast should be swapped.
This runs fine:

select sum(cast(testclass0_.Int32Prop as BIGINT)) as col_0_0_ from TestClass testclass0_

Test class and mapping:

public class TestClass {
    public virtual int Id { get; set; }
    public virtual int? Int32Prop { get; set; }
}

public class TestClassMap : ClassMap<TestClass> {
    public TestClassMap() {
        Table("TestClass");
        Id(i => i.Id);
        Map(i => i.Int32Prop);
    }
}
@AlekseyMartynov
Copy link
Author

UPDATE

The bug is reproduced only with Nullable properties.
For plain int, two cast are issued and no exception occurs:

select cast(sum(cast(testclass0_.Int32Prop as BIGINT)) as BIGINT) as col_0_0_ from TestClass testclass0_

@maca88
Copy link
Contributor

maca88 commented Mar 2, 2019

Made a PR that fixes the issue with nullable types and also reduces the cast usage. For your example only one cast will be generated for int and int?.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants