Skip to content

Cannot retrieve entries with decimal.MaxValue from database #1378

Closed

Description

@gmarokov

Using EF core with Npgsql v.2.1 I have a model which have a decimal.MaxValue. Save is ok but whenever I need to retrieve the data I get this error:

Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware:Error: An unhandled exception has occurred while executing the request.

System.InvalidOperationException: No row is available
   at Npgsql.NpgsqlDefaultDataReader.GetFieldValue[T](Int32 column) in C:\projects\npgsql\src\Npgsql\NpgsqlDefaultDataReader.cs:line 130
   at lambda_method(Closure , DbDataReader )

Parsing to Int32 looks suspicious. My db data type is numeric.

Activity

  1. roji commented on May 19, 2020

    @roji
    Member

    @gmarokov a minimal code sample would be helpful here.

    @YohDeadfall want to take a look?

  2. self-assigned this
    on May 19, 2020
  3. gmarokov commented on May 22, 2020

    @gmarokov
    Author

    @roji thanks for the fast reply! I will try to provide code sample.

    To start with the very simple model I have:

    public class User
    {
        public int Key { get; set; }
        public decimal Balance { get; set; }
    }
    

    Here comes the straight forward DbContext and a seed method where I create sample Users:

    public class MainDbContext : DbContext
    {
        public DbSet<User> Users { get; set; }
        public MainDbContext(DbContextOptions<MainDbContext> options) : base(options) { }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            MainDbSeed.Seed(modelBuilder);
        }
    }
    
    public class MainDbSeed
    {
        public static void Seed(ModelBuilder modelBuilder)
        {
            User users = new User[10];
            var balance = decimal.MaxValue;
    	for(int i = 0; i < users.Length; i++)
    	{
    	     var id = i + 1;
    	     users[i] = new User()
    	     {
    	         UserId = id,
    		 Balance = balance
    	     };
    	}
            modelBuilder.Entity<User>().HasData(users);
        }
    }
    

    So far so good. If I query the Balance column I get 79228162514264337593543950335.
    But when I query the user with User user = await mainDbContext.Users.FirstOrDefaultAsync(); I get the error described.
    This is the property for the db column: Name: Balance, Data type: numeric, Not null: true the rest is default.
    Forgot to mention that I user docker image to run Postgresql which is the following postgres:10.5.
    Also I use package driver version: <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="2.1.2" />

    Hope that helps.

  4. roji commented on Jun 7, 2020

    @roji
    Member
  5. YohDeadfall commented on Jun 7, 2020

    @YohDeadfall
    Contributor

    @gmarokov which version of Npgsql you're using? There should be no issue, moreover we even have a test for this.

  6. gmarokov commented on Jun 8, 2020

    @gmarokov
    Author

    @gmarokov which version of Npgsql you're using? There should be no issue, moreover we even have a test for this.

    Hey @YohDeadfall. I use official docker image for 10.5. My EF driver is using package version 2.1.2

  7. YohDeadfall commented on Jun 8, 2020

    @YohDeadfall
    Contributor

    Checked dependency via NuGet. You're using v4.0.3 which should be fine with decimal.MaxValue too (source). Okay, I will check it closely.

  8. roji commented on Jan 26, 2021

    @roji
    Member

    Am closing this for age, and as we don't think we have a bug here. @gmarokov if you still think there's an issue on the Npgsql side - after updating to the latest version - please post back and we'll reopen if necessary.

  9. MonticolaExplorator commented on Dec 8, 2022

    @MonticolaExplorator

    Sorry to bring this back to life, but I think I am facing the same issue. I cannot round trip a decimal.MaxValue with Entity Framework on Postgres. Here is my sample code, very similar to what was originaly posted. Using:

    • Microsoft.EntityFrameworkCore 7.0.0
    • Npgsql.EntityFrameworkCore.PostgreSQL 7.0.0
    • Npgsql 7.0.0

    This is my sample entity with a decimal property.

    public class BankAccount
    {
        public int Id { get; set; }
        public string? Currency { get; set; }
        public decimal Quantity { get; set; }
    }
    

    This is my context class. The 31,2 is just an example. The logic I try to follow is having a numeric with X number of digits to the right of the decimal point. An then have 29+X as precision, because the max decimal value is an integer with 29 digits.

    public class Context:DbContext
    {
        public string ConnectionString { get; }
    
        public Context(string connectionString)
        {
            ConnectionString = connectionString;
        }
    
        public DbSet<BankAccount> Amounts { get; set; }
    
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            base.OnConfiguring(optionsBuilder);
            optionsBuilder.UseNpgsql(ConnectionString);
        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            
            modelBuilder.Entity<BankAccount>( bankAccount =>
            {
                bankAccount.Property(a => a.Currency).IsRequired().HasMaxLength(32);
                bankAccount.Property(a => a.Quantity).IsRequired().HasPrecision(31,2);
            });
        }
    }
    

    Finally, this is the code with which I reproduce the issue (the body of my main function). You can execute it, you just have to provide a connection string.

    using NetSamples.EntityFramework;
    using NetSamples.EntityFramework.Domain;
    
    //decimal.maxvalue roundtripping
    var connectionString = "";
    using (var context = new Context(connectionString))
    {
        context.Database.EnsureDeleted();
        context.Database.EnsureCreated();
        var amount = new BankAccount()
        {
            Currency = "Eur",
            Quantity = decimal.MaxValue
        };
        context.Amounts.Add(amount);
        context.SaveChanges();
    }
    
    using (var context = new Context(connectionString))
    {
        var amount = context.Amounts.Single();
    }
    

    When I run it, I get an System.IndexOutOfRangeException: 'Index was outside the bounds of the array.' when querying the database with var amount = context.Amounts.Single();.

    I have read other related issues like Numeric value does not fit in a System.Decimal and Numeric value does not fit in a System.Decimal. But haven't found a solution to this issue (sorry if I missed it), except using Npgsql Numeric type. Using Numeric could be a solution for me, but not a simple one since the software I am writing will have to run on Oracle and SQL Server as well.

    If I understand things correctly, the problem is that the final representation of decimal.MaxValue on the numeric(31,2) changes slightly. From 79228162514264337593543950335, it ends up being 79228162514264337593543950335.00 on the database. And I agree that the correct thing to do when the driver tries to read this value into a .NET decimal is to fail, because they are not the same value and silently loosing precision is sketchy.

    At the same time, I believe there should be a simple way to use the whole decimal range on Entity Framework.

    Maybe it is rare to really need to push the range of needed values so far. Probably most applications don't really need that and if they face this issue they might as well just change their code. My problem is that I am porting an existing solution, that has already been deployed on many clients and doing this change is complex and very error prone.

    Is there any way around this issue? Thanks a lot.

  10. roji commented on Dec 8, 2022

    @roji
    Member

    @MonticolaExplorator removing HasPrecision(31,2) from your property makes the code sample work, and does roundtrip the value. I haven't looked at this in-depth, but I suspect that adding the two trailing fractional digits makes the number go out of the .NET decimal range.

    [...] except using Npgsql Numeric type [...]

    Which type are you referring to, and which Npgsql version are you using?

  11. MonticolaExplorator commented on Dec 8, 2022

    @MonticolaExplorator

    Oh, my bad. I probably did not pay enough attention to those other threads. And I had not read Postgres numeric documentation.

    without any precision or scale creates an “unconstrained numeric” column in which numeric values of any length can be stored, up to the implementation limits

    Every time I read something about omitting precision and scale, I asumed that it achieved certain default precision and scale that fitted a particular need, I did not know about unconstrained numerics. Neat!

    Which type are you referring to, and which Npgsql version are you using?

    Sorry, again, my fault. On one of the threads I read something about a hypothetical Npgsql-specific numeric type and asumed it existed. I was testing with version 7.0.0 of the three nuget packages (Entity Framework Core, Npgsql.EntityFrameworkCore.PostgreSQL, Npgsql), but my original development uses 6.0.2.

    Thank you very much for your pattience @roji .

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions