2

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?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • Are you using entity-framework ? or entity-framework core ? if in the first case (if your question tagging is correct) are you using an edmx to map classes to your database ? – Irwene Sep 23 '22 at 15:08

1 Answers1

5

You need to specify the decimal's precision. For example:

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

precision depends on your SQL Column definition. See column properties dialog: Numeric precision in SQL Properties dialog

Bron Davies
  • 5,930
  • 3
  • 30
  • 41
  • 1
    Because if you don't specify precision and scale, you'll get `decimal(38,0)` in SQL Server - **no** digits after the decimal point! That's what's causing the "out of range" error .... – marc_s Sep 23 '22 at 17:16