gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:20:11 24 4
gpt4 key购买 nike

从 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] 

运行无溢出

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

关于c# - 如何在聚合之前将值转换为 long ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53153382/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com