Repository navigation
Closed
Description
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;
}
#endregionThe 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);
});Metadata
Metadata
Assignees
Labels
No labels
Activity
takerukoushirou commentedon May 31, 2018
With release version 2.1, the exception has changed as follows:
The statistics class has a decimal property:
which is translated as follows in the migrations snapshot:
The table created by PostgreSQL has the following structure:
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.
[-]"InvalidOperationException: No row is available" in NpgsqlDefaultDataReader using LazyLoader[/-][+]Numeric value does not fit in a System.Decimal[/+]takerukoushirou commentedon May 31, 2018
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:


After modifying the value (and actually setting it back to the same number) the binary representation has changed and no exception occurs:
According to the PostgreSQL source code, the bits different is the display scale value (
numeric.c, line 245ff):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.
YohDeadfall commentedon May 31, 2018
Yes, the numeric handler was changed (npgsql/npgsql#1959). I'll take a look on the problem. Thanks for reporting!
mortenjus commentedon May 31, 2018
Same problem, using a lot of decimals, i.e.
5900992.4841569237337247113698
Rounding it works
roji commentedon May 31, 2018
@YohDeadfall, move to the npgsql repo for 4.0.1?
mortenjus commentedon May 31, 2018
It's in my case easily avoidable by controlling the amount of decimals..
YohDeadfall commentedon May 31, 2018
The value of
dscaleis1Ewhich is decimal 30, but the .NETdecimaltype 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
numerictype does. See npgsql/npgsql#448.takerukoushirou commentedon May 31, 2018
@YohDeadfall In this particular case I am not configuring anything specifically; the default mapping for a .NET
decimalfrom the Npgsql EF Core provider is being used which is seemingly justnumeric. With the recent changes being introduced in Npgsql, the provider should then probably limit the scale to 28 for a .NETdecimalwhen creating a migration, if nothing else is specified.YohDeadfall commentedon May 31, 2018
@roji Is it possible to implement?
takerukoushirou commentedon May 31, 2018
@YohDeadfall @roji Would it also be possible to quietly return a .NET
decimalwith some loss of precision? I am sure there are installations with columns that were created asnumericthat 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
IgnoreDecimalLossOfPrecisionor similar).YohDeadfall commentedon Jun 1, 2018
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:
43 remaining items
YohDeadfall commentedon Nov 13, 2018
@JwanKhalaf You should round values stored in the database using the script above. After that the driver will be able to read them.
maciey commentedon Apr 25, 2019
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
YohDeadfall commentedon Apr 25, 2019
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.
maciey commentedon May 3, 2019
Thanks replying. Can you please previous version I can use for that?
YohDeadfall commentedon May 3, 2019
You can use the code from npgsql/npgsql@f0757eb.
maciey commentedon Jun 12, 2019
Ive tried this revision and still have exception
Numeric value does not fit in a System.Decimal
in GetValue()
roji commentedon Jun 12, 2019
@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.
arthur-pinheiro commentedon Jul 9, 2020
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.
YohDeadfall commentedon Jul 9, 2020
Just find all columns of the numeric type from
pg_attributetable and corresponding tables by joiningpg_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 (:
arthur-pinheiro commentedon Jul 9, 2020
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?
arthur-pinheiro commentedon Jul 10, 2020
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!
YohDeadfall commentedon Jul 10, 2020
Will take a look in couple of days. Otherwise, ping me (:
roji commentedon Jul 10, 2020
@arthur-pinheiro can you please open a new issue for this so we're sure it doesn't get lost?
arthur-pinheiro commentedon Jul 10, 2020
Sure! I'll do it now, thanks!
Raniz85 commentedon Feb 7, 2024
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: