简体   繁体   English

十进制超出范围 C# 和 SQL 服务器

[英]Decimal out of range C# and SQL Server

I have a C# Entity Framework class like this:我有一个 C# 实体框架 class 像这样:

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

In the database, this value is stored something like this:在数据库中,这个值是这样存储的:

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

Then when I go to run this code:然后当我 go 运行这段代码时:

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

(It should fail on save changes) (它应该在保存更改时失败)

I seem to get this exception:我似乎得到了这个例外:

Parameter value '2509067194275615035776.00' is out of range.参数值“2509067194275615035776.00”超出范围。

I tried to insert that value manually in SQL Server Management Studio and it seemed to work ok...我试图在 SQL Server Management Studio 中手动插入该值,它似乎工作正常......

Mind you this was recently changed from a long in C# and a bigint in SQL Server to a decimal in C# and a decimal in SQL Server... Mind you this was recently changed from a long in C# and a bigint in SQL Server to a decimal in C# and a decimal in SQL Server...

I also have this config class that looks something like this and maps the C# object to the database...我也有这个配置 class 看起来像这样并将 C# object 映射到数据库...

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

I don't know why I'm getting this exception as it does not seem bigger than the decimal max value in SQL Server....我不知道为什么会出现此异常,因为它似乎不大于 SQL 服务器中的十进制最大值......

I'm a bit new to Entity Framework, so maybe I'm missing some other config somewhere?我对 Entity Framework 有点陌生,所以也许我在某处遗漏了一些其他配置?

You need to specify the decimal's precision.您需要指定小数的精度。 For example:例如:

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

precision depends on your SQL Column definition.精度取决于您的 SQL 列定义。 See column properties dialog:查看列属性对话框: SQL 属性对话框中的数值精度

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM