Home > Software engineering >  Decimal out of range C# and SQL Server
Decimal out of range C# and SQL Server

Time:09-27

I have a C# Entity Framework class like this:

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:

 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.

I tried to insert that value manually in SQL Server Management Studio and it seemed to work ok...

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...

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....

I'm a bit new to Entity Framework, so maybe I'm missing some other config somewhere?

CodePudding user response:

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. See column properties dialog: Numeric precision in SQL Properties dialog

  • Related