从 EF core 2.1.4 开始,如果我们在聚合之前将 int
值转换为 long
或 long?
(可能是为了避免算术溢出),此转换不会影响生成的查询,并且无论如何都会发生溢出。
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]
运行无溢出
对于 future 的读者。这真的取决于 ORM 并且它可能并非在所有情况下都有效
关于c# - 如何在聚合之前将值转换为 long ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53153382/