Skip to content

Numeric value does not fit in a System.Decimal #438

Closed

Description

@takerukoushirou

Since build 2.1.0-rtm-ci.305 lazy loading a one-to-many entity collection fails with the following exception:

InvalidOperationException: No row is available
Npgsql.NpgsqlDefaultDataReader.GetFieldValue<T>(int column) in C:\projects\npgsql\src\Npgsql\NpgsqlDefaultDataReader.cs, line 136

Stack
InvalidOperationException: No row is available
Npgsql.NpgsqlDefaultDataReader.GetFieldValue<T>(int column) in C:\projects\npgsql\src\Npgsql\NpgsqlDefaultDataReader.cs
lambda_method(Closure , DbDataReader )
Microsoft.EntityFrameworkCore.Storage.Internal.TypedRelationalValueBufferFactory.Create(DbDataReader dataReader)
Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable<T>+Enumerator.BufferlessMoveNext(DbContext _, bool buffer)
Microsoft.EntityFrameworkCore.Storage.ExecutionStrategy.ExecuteImplementation<TState, TResult>(Func<DbContext, TState, TResult> operation, Func<DbContext, TState, ExecutionResult<TResult>> verifySucceeded, TState state)
Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable<T>+Enumerator.MoveNext()
Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider._TrackEntities<TOut, TIn>(IEnumerable<TOut> results, QueryContext queryContext, IList<EntityTrackingInfo> entityTrackingInfos, IList<Func<TIn, object>> entityAccessors)+MoveNext()
Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider+ExceptionInterceptor<T>+EnumeratorExceptionInterceptor.MoveNext()
Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.Load<TSource>(IQueryable<TSource> source)
Microsoft.EntityFrameworkCore.Internal.EntityFinder<TEntity>.Load(INavigation navigation, InternalEntityEntry entry)
Microsoft.EntityFrameworkCore.Internal.LazyLoader.Load(object entity, string navigationName)
Microsoft.EntityFrameworkCore.Infrastructure.LazyLoaderExtensions.Load<TRelated>(ILazyLoader loader, object entity, ref TRelated navigationField, string navigationName)
[...].Article.get_Statistics() in Article.cs
            get => _statistics ?? LazyLoader?.Load(this, ref _statistics);

Build 2.1.0-rtm-ci.304 works fine without any issues. Since dependencies on Npgsql and EFCore are unchanged between the two builds, this seems to have been introduced with changes between the two builds.

I'm using a simple lazy loader configuration in Article.cs:

        public virtual ICollection<ArticleStatistic> Statistics
        {
            get => _statistics ?? LazyLoader?.Load(this, ref _statistics);
            set => _statistics = value;
        }

        private ICollection<ArticleStatistic> _statistics;

        #region Lazy Loader

        private ILazyLoader LazyLoader { get; set; }

        public Article()
        {
        }

        [UsedImplicitly]
        public Article(ILazyLoader lazyLoader)
        {
            LazyLoader = lazyLoader;
        }

        #endregion

The relationship is not further described with the fluent API, using a standard one-to-many relationship as can be seen in the model snapshot:

            modelBuilder.Entity(
                "[...].ArticleStatistic", b => {
                    b.HasOne("[...].Article", "Entity")
                     .WithMany("Statistics")
                     .HasForeignKey("EntityId")
                     .OnDelete(DeleteBehavior.Cascade);
                });

Activity

  1. takerukoushirou commented on May 31, 2018

    @takerukoushirou
    ContributorAuthor

    With release version 2.1, the exception has changed as follows:

    OverflowException: Numeric value does not fit in a System.Decimal
    Npgsql.NpgsqlDefaultDataReader.GetFieldValue<T>(int column) in C:\projects\npgsql\src\Npgsql\NpgsqlDefaultDataReader.cs, line 159
    
    Stack
    OverflowException: Numeric value does not fit in a System.Decimal
    Npgsql.NpgsqlDefaultDataReader.GetFieldValue<T>(int column) in C:\projects\npgsql\src\Npgsql\NpgsqlDefaultDataReader.cs
    lambda_method(Closure , DbDataReader )
    Microsoft.EntityFrameworkCore.Storage.Internal.TypedRelationalValueBufferFactory.Create(DbDataReader dataReader)
    Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable<T>+Enumerator.BufferlessMoveNext(DbContext _, bool buffer)
    Microsoft.EntityFrameworkCore.Storage.ExecutionStrategy.ExecuteImplementation<TState, TResult>(Func<DbContext, TState, TResult> operation, Func<DbContext, TState, ExecutionResult<TResult>> verifySucceeded, TState state)
    Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable<T>+Enumerator.MoveNext()
    Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider._TrackEntities<TOut, TIn>(IEnumerable<TOut> results, QueryContext queryContext, IList<EntityTrackingInfo> entityTrackingInfos, IList<Func<TIn, object>> entityAccessors)+MoveNext()
    Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider+ExceptionInterceptor<T>+EnumeratorExceptionInterceptor.MoveNext()
    Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.Load<TSource>(IQueryable<TSource> source)
    Microsoft.EntityFrameworkCore.Internal.EntityFinder<TEntity>.Load(INavigation navigation, InternalEntityEntry entry)
    Microsoft.EntityFrameworkCore.Internal.LazyLoader.Load(object entity, string navigationName)
    Microsoft.EntityFrameworkCore.Infrastructure.LazyLoaderExtensions.Load<TRelated>(ILazyLoader loader, object entity, ref TRelated navigationField, string navigationName)
    [...].Article.get_Statistics() in Article.cs
    

    The statistics class has a decimal property:

    public decimal Value { get; set; }

    which is translated as follows in the migrations snapshot:

                modelBuilder.Entity(
                    "[...].ArticleStatistic", b => {
                        b.Property<int>("Id")
                         .ValueGeneratedOnAdd()
                         .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn);
    
                        b.Property<Guid>("EntityId");
    [...]
                        b.Property<decimal>("Value");
    
                        b.ToTable("ArticleStatistics");
                    });

    The table created by PostgreSQL has the following structure:

    create table "ArticleStatistics"
    (
      "Id"           serial                   not null
        constraint "PK_ArticleStatistics"
        primary key,
    [...]
      "EntityId"     uuid                     not null
        constraint "FK_ArticleStatistics_Articles_EntityId"
        references "Articles"
        on delete cascade,
      "Value"        numeric                  not null
    );

    I found one entity where the problem does not show up, and that entity was recently edited. So I tried modifying some statistics and depending on the numeric value, the problem appears or not. In one example the issue appeared due to one value being 22. I changed it to six and the query succeeded, and awkwardly enough changing it back to 22 it still works. Maybe some internal were changed that affect Npgsql and are not visible in the rendered value. Originally this specific value though was an integer that was converted into a .NET decimal before insertion.

    I also checked whether the issue appears if I directly query on the statistics set of the DbContext in a console app, and it does. Thus this issue is not related to lazy loading.

  2. changed the title [-]"InvalidOperationException: No row is available" in NpgsqlDefaultDataReader using LazyLoader[/-] [+]Numeric value does not fit in a System.Decimal[/+] on May 31, 2018
  3. takerukoushirou commented on May 31, 2018

    @takerukoushirou
    ContributorAuthor

    I looked at the binary representation and discovered the following; originally values (5, 0 and 0) inserted via Npgsql (roughly two months ago) that lead to the exception:
    binary numeric existing
    After modifying the value (and actually setting it back to the same number) the binary representation has changed and no exception occurs:
    binary numeric updated

    According to the PostgreSQL source code, the bits different is the display scale value (numeric.c, line 245ff):

    dscale, or display scale, is the nominal precision expressed as number of digits after the decimal point (it must always be >= 0 at present). dscale may be more than the number of physically stored fractional digits, implying that we have suppressed storage of significant trailing zeroes. It should never be less than the number of stored digits, since that would imply hiding digits that are present. NOTE that dscale is always expressed in decimal digits, and so it may correspond to a fractional number of base-NBASE digits --- divide by DEC_DIGITS to convert to NBASE digits.

    So far it seems handling of dscale changed and values written with an earlier version of the Npgsql EF Core provider now lead to the exception present here.

  4. YohDeadfall commented on May 31, 2018

    @YohDeadfall
    Contributor

    Yes, the numeric handler was changed (npgsql/npgsql#1959). I'll take a look on the problem. Thanks for reporting!

  5. self-assigned this
    on May 31, 2018
  6. mortenjus commented on May 31, 2018

    @mortenjus

    Same problem, using a lot of decimals, i.e.
    5900992.4841569237337247113698
    Rounding it works

  7. modified the milestone: 2.1.1 on May 31, 2018
  8. roji commented on May 31, 2018

    @roji
    Member

    @YohDeadfall, move to the npgsql repo for 4.0.1?

  9. mortenjus commented on May 31, 2018

    @mortenjus

    It's in my case easily avoidable by controlling the amount of decimals..

  10. YohDeadfall commented on May 31, 2018

    @YohDeadfall
    Contributor

    The value of dscale is 1E which is decimal 30, but the .NET decimal type supports scale up to 28 and stores values differently (source). The behavior was changed because of npgsql/npgsql#1921. So you should limit the scale for the column.

    FYI, we plan to implement a new type which will store the same range of values as the PostgreSQL numeric type does. See npgsql/npgsql#448.

  11. takerukoushirou commented on May 31, 2018

    @takerukoushirou
    ContributorAuthor

    @YohDeadfall In this particular case I am not configuring anything specifically; the default mapping for a .NET decimal from the Npgsql EF Core provider is being used which is seemingly just numeric. With the recent changes being introduced in Npgsql, the provider should then probably limit the scale to 28 for a .NET decimal when creating a migration, if nothing else is specified.

  12. YohDeadfall commented on May 31, 2018

    @YohDeadfall
    Contributor

    @roji Is it possible to implement?

  13. takerukoushirou commented on May 31, 2018

    @takerukoushirou
    ContributorAuthor

    @YohDeadfall @roji Would it also be possible to quietly return a .NET decimal with some loss of precision? I am sure there are installations with columns that were created as numeric that would break after a provider upgrade without either adding a migration or manually modifying the database column to reduce the scale.
    This would ensure compatibility with existing applications (or alternatively as a configuration option IgnoreDecimalLossOfPrecision or similar).

  14. YohDeadfall commented on Jun 1, 2018

    @YohDeadfall
    Contributor

    It's possible, but I'm not sure that it's a good idea to round values in the numeric handler because it should return values as is. @roji what do think about that?

    As a workaround you can execute the following query to fix the issue:

    UPDATE "ArticleStatistic" SET "Value" = round("Value", 28);
  15. 43 remaining items

  16. YohDeadfall commented on Nov 13, 2018

    @YohDeadfall
    Contributor

    @JwanKhalaf You should round values stored in the database using the script above. After that the driver will be able to read them.

  17. maciey commented on Apr 25, 2019

    @maciey

    Cant this be fixed other way then using scripts ?
    Im perfectly fine npgsql to scale down long numbers to .NET max precision

    Maybe some config param etc
    I dont want use scripts / rounding in each query. jdbc drivers play well with that

  18. YohDeadfall commented on Apr 25, 2019

    @YohDeadfall
    Contributor

    We do not plan to support that scenario, but since Npgsql is extensible you can write your own handler taking existing one as a base, or just copy code of the previous version.

  19. maciey commented on May 3, 2019

    @maciey

    Thanks replying. Can you please previous version I can use for that?

  20. YohDeadfall commented on May 3, 2019

    @YohDeadfall
    Contributor

    You can use the code from npgsql/npgsql@f0757eb.

  21. maciey commented on Jun 12, 2019

    @maciey

    You can use the code from npgsql/npgsql@f0757eb.

    Ive tried this revision and still have exception
    Numeric value does not fit in a System.Decimal

    in GetValue()

  22. roji commented on Jun 12, 2019

    @roji
    Member

    @maciey have you used the script that @YohDeadfall pointed to? As he wrote above, we don't plan to change Npgsql to transparently/implicitly round down values for you, as that would be dangerous precision loss. It's better to fix the issue at the database.

  23. arthur-pinheiro commented on Jul 9, 2020

    @arthur-pinheiro

    Hello guys. I'm facing the same issue since I've updated .net framework from 4.0 to 4.7.2 and npgsql from 2.0.14.3 to version 4.1.3.1. I tried to keep npg in version 2.0.14.3, the problem persists. We have a large system and numeric data is present in almost all tables and views. Is there any solution? I've seen that there's @YohDeadfall script, but it's very complicated to seek for all columns with numeric data with values to fix. Thanks in advance.

  24. YohDeadfall commented on Jul 9, 2020

    @YohDeadfall
    Contributor

    Just find all columns of the numeric type from pg_attribute table and corresponding tables by joining pg_class. After this just run the script for all of them.

    I oversimplified the solution because there are record types and so on, but you got the idea (:

  25. arthur-pinheiro commented on Jul 9, 2020

    @arthur-pinheiro

    Hello @YohDeadfall. Thanks for the solution. I did it and it worked for reading the records, but for saving data the problem still exists. For example, in our application we have an decimal input field (variable x), and it's value is saved into the database, BUT first we do some calculation: decimal valueToBeStored = x / 60. Nice, the value'll be persisted correctly (the value saved in the database = 0.5126666666666666666666666667). When I try to read it, the same error occurs, so I'd have to run the script again, to fix this value :( Is there any other solution not having to round the value before saving it or before reading it into my decimal variable?

  26. arthur-pinheiro commented on Jul 10, 2020

    @arthur-pinheiro

    Good morning everyone. I'm sorry to be here again, but it seems like a npgsql bug. In this simple program I save the decimal variable 0.5126666666666666666666666667 (which has 28 decimal digits) into the database (so this value fits into a c# decimal value). It works perfectly. When I try to read it from the database, it throws 'numeric value does not fit in a system.decimal'. Can anyone help me? Maybe it's a misunderstanding from me. Thanks!

    Screenshot_13

  27. YohDeadfall commented on Jul 10, 2020

    @YohDeadfall
    Contributor

    Will take a look in couple of days. Otherwise, ping me (:

  28. roji commented on Jul 10, 2020

    @roji
    Member

    @arthur-pinheiro can you please open a new issue for this so we're sure it doesn't get lost?

  29. arthur-pinheiro commented on Jul 10, 2020

    @arthur-pinheiro

    @arthur-pinheiro can you please open a new issue for this so we're sure it doesn't get lost?

    Sure! I'll do it now, thanks!

  30. Raniz85 commented on Feb 7, 2024

    @Raniz85

    I just had this issue in a LINQ query (i.e. I can't update the database tables) where an expression resulted in numerics with too high scale to fit in a decimal.

    The solution is to use Decimal.Round(<expression>, <acceptable precision>) in the query.

    Something like:

    var query = from order in db.Orders
        join detail in db.OrderDetails
        on order.OrderID equals detail.OrderID
        group detail by order.OrderID into grouped
        select new
        {
            OrderID = grouped.Key,
            AverageQuantity = Decimal.Round(grouped.Sum(x => x.Quantity) / grouped.Count(), 10)
        };
    
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