c# - 小数超出范围 C# 和 SQL Server

标签 c# sql-server entity-framework decimal

我有一个像这样的 C# Entity Framework 类:

public class Card 
{
    public decimal CardNumber { get; set; }
}

在数据库中,该值的存储方式如下:

[card_number] [decimal](38, 2) NULL

然后当我去运行这段代码时:

 entities.Set<Card>().Add(card);
 entities.SaveChanges();

(保存更改应该会失败)

我似乎遇到了这个异常:

Parameter value '2509067194275615035776.00' is out of range.

我尝试在 SQL Server Management Studio 中手动插入该值,它似乎工作正常...

请注意,最近这已从 C# 中的 long 和 SQL Server 中的 bigint 更改为 C# 中的 decimal 和 SQL Server 中的 decimal SQL 服务器...

我还有这个配置类,看起来像这样,并将 C# 对象映射到数据库...

public class CardConfiguration : TrackedEntityConfiguration<Card>
{
    public CardConfiguration()
    {
        ToTable("Card", "dbo");
       
        Property(c => c.CardNumber)
             .HasColumnName("card_number") 
             .IsRequired();
    }
}

我不知道为什么会收到此异常,因为它似乎不大于 SQL Server 中的小数最大值......

我对 Entity Framework 有点陌生,所以也许我在某个地方缺少一些其他配置?

最佳答案

您需要指定小数的精度。例如:

Property(c => c.CardNumber).HasColumnName("card_number").HasPrecision(18, 6);

精度取决于您的 SQL 列定义。请参阅列属性对话框: Numeric precision in SQL Properties dialog

关于c# - 小数超出范围 C# 和 SQL Server,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73829696/

相关文章:

c# - 计算重叠日期的住宿天数

sql-server - TFS 数据库部署解决方案

c# - 如何在 SQL Server 2008 中存储和检索 .pdf、.exe 文件

java - JPA TABLE_PER_CLASS继承: abstract entity table created

c# - 代码优先 : Create Tables but not database

c# - 进行内容协商时不使用 SupportedMediaTypes

c# - Linux 上的 .Net Web 服务

sql-server - 在 SQL Server 链接连接中添加参数

entity-framework - 配置 Entity Framework 以加载预定义的对象

c# - 对 IQueryable OfType<> 的反射(reflection)