Skip to content

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

Closed
@AlekseyMartynov

Description

@AlekseyMartynov

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);
    }
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions