如何在聚合之前将值转换为 long ?

How to cast a value to long before aggregating it?

从 EF core 2.1.4 开始,如果我们在聚合前将 int 值转换为 longlong?(可能是为了避免算术溢出),此转换不会影响生成的查询和溢出无论如何都会发生。

using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;

namespace EfCoreBugs
{
  class Program
  {
    static void Main(string[] args)
    {
      using (var dbContext = new MyDbContext())
      {
        Console.WriteLine(dbContext.Payments.Sum(x => (long?)x.Amount));
      }
      Console.ReadLine();
    }

    public class MyDbContext : DbContext
    {
      protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
      {
        optionsBuilder.UseSqlServer(@"Server=.;Database=EfCoreBugs;Trusted_Connection=True;MultipleActiveResultSets=True;");
      }
      public DbSet<Payment> Payments { get; set; }
    }

    public class Payment
    {
      public int Id { get; set; }
      public int Amount { get; set; }
    }
  }
}

生成的查询是:

SELECT SUM([x].[Amount])
FROM [Payments] AS [x]

有什么办法可以解决这个溢出问题吗? (除了将 Amount 的数据类型更改为 long

尝试Convert.ToInt64(x.Amount)

它可能会翻译成

SELECT SUM(CONVERT(bigint, [x].[Amount])) FROM [Payments] AS [x] 

和运行没有溢出

对于未来的读者。这真的取决于 ORM 并且它可能并非在所有情况下都有效