Repository navigation
Not planned
Description
| Environment | |
|---|---|
| PostgreSQL | 18.6 (postgres:18), session TimeZone Etc/UTC |
| .NET 10 | runtime 10.0.11, Npgsql.EntityFrameworkCore.PostgreSQL 10.0.3, EF Core 10.0.4 |
| .NET 11 | runtime 11.0.0-rc.2, Npgsql.EntityFrameworkCore.PostgreSQL 11.0.0-rc.2, EF Core 11.0.0-rc.2 |
| Also | Npgsql 10.0.3 on both lines, macOS arm64 |
Both lines print the same output. main at 150011d has the same code.
| LINQ | Row | .NET | PostgreSQL | SQL |
|---|---|---|---|---|
(int)r.Decimal |
2.7m | 2 | 3 | r."Decimal"::int |
(long)r.Double |
2.7 | 2 | 3 | r."Double"::bigint |
(byte)r.Int == 249 |
−7 | match | no match | r."Int"::smallint = 249 |
r.Big / r.Big2 == 3 |
7 / 2 | match | no match | r."Big" / r."Big2" = 3 |
Repro
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System.Numerics;
await using var context = new TestContext();
await context.Database.EnsureDeletedAsync();
await context.Database.EnsureCreatedAsync();
context.Rows.Add(new Row { Decimal = 2.7m, Double = 2.7, Int = -7, Big = 7, Big2 = 2 });
await context.SaveChangesAsync();
var row = await context.Rows.AsNoTracking().SingleAsync();
// 1. C# casts truncate toward zero; ::int rounds
Console.WriteLine($"(int)2.7m: .NET {(int)row.Decimal}, database {await context.Rows.Select(r => (int)r.Decimal).SingleAsync()}");
Console.WriteLine($"(long)2.7: .NET {(long)row.Double}, database {await context.Rows.Select(r => (long)r.Double).SingleAsync()}");
// 2. An unchecked byte cast wraps; ::smallint keeps -7
Console.WriteLine($"(byte)-7 == 249: .NET {((byte)row.Int == 249 ? 1 : 0)}, database {await context.Rows.CountAsync(r => (byte)r.Int == 249)}");
// 3. BigInteger division is integer division
Console.WriteLine($"Big / Big2 == 3 (7 / 2): .NET {(row.Big / row.Big2 == 3 ? 1 : 0)}, database {await context.Rows.CountAsync(r => r.Big / r.Big2 == 3)}");
public class TestContext : DbContext
{
public DbSet<Row> Rows => Set<Row>();
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder
.UseNpgsql(Environment.GetEnvironmentVariable("Test__Npgsql__DefaultConnection"), o => o.UseNodaTime())
.LogTo(Console.WriteLine, LogLevel.Information)
.EnableSensitiveDataLogging();
}
public class Row
{
public int Id { get; set; }
public decimal Decimal { get; set; }
public double Double { get; set; }
public int Int { get; set; }
public BigInteger Big { get; set; }
public BigInteger Big2 { get; set; }
}Output, the same on both lines:
(int)2.7m: .NET 2, database 3
(long)2.7: .NET 2, database 3
(byte)-7 == 249: .NET 1, database 0
Big / Big2 == 3 (7 / 2): .NET 1, database 0
- Casts. C# casts from
decimal,doubleandfloatto an integer type truncate toward zero. PostgreSQL's casts round: half away from zero fornumeric, half to even forfloat8. SQL Server'sCASTtruncates, so this is specific to this provider. The cast is rendered as::int(NpgsqlQuerySqlGenerator.cs#L603-L626);trunc(x)::intwould match .NET.Convert.ToInt32(decimal)goes the same way (NpgsqlConvertTranslator.cs#L36) and rounds half away from zero, where .NET rounds half to even. bytemaps tosmallint, so an unchecked(byte)cast keeps −7 instead of wrapping to 249.BigIntegermaps tonumeric(NpgsqlBigIntegerTypeMapping.cs#L30), so/is numeric division (3.5).div(a, b)matchesBigInteger's truncating division.
Metadata
Metadata
Assignees
Labels
No labels
Activity
Zentauer commentedon Nov 24, 2026
Hey, I'd love to help. These three cases seem quite different to me, so it might make sense to handle them separately.
The
BigIntegerdivision looks like a clear bug with a small fix. I would translate/between twoBigIntegeroperands to PostgreSQL'sdiv(a, b), which truncates towards zero just likeBigInteger.Dividein .NET. The change would go intoNpgsqlSqlTranslatingExpressionVisitor.VisitBinary, similar to the existing special case forLocalDatesubtraction, and I would add aDividetest toBigIntegerTranslationsTest.The rounding in numeric casts seems more like a design decision, since switching to
trunc()could change results for existing applications and affect index usage. The wrapping behavior of(byte)casts is probably hard to support, since PostgreSQL has no 1-byte integer type. I think both points should be clarified before any changes are made.Would a PR for the
BigIntegerdivision part be welcome?roji commentedon Nov 24, 2026
@CaffeinatedCoder thank you for these bug reports, but can you please open individual issues for separate problems? Your issues have clumped together unrelated problems, making it difficult to track things properly.
Am happy to receive individual bug reports (and PRs fixing them) - @Zentauer feel free to open a separate issue for that and a PR etc.
CaffeinatedCoder commentedon Nov 24, 2026
@roji Sorry for the inconvenience; I initially wanted to avoid opening a huge load of issues and tried to relate them as closely together by affected coarse subject. I will split them into separate issues.
CaffeinatedCoder commentedon Nov 24, 2026
@roji I've split the bundled issues as you asked: one issue per bug, each with its own repro, re-run on 10.0.4 and 11.0.0.
From this issue:
decimal,doubleandfloatto an integer type round instead of truncating #4157 casts fromdecimal/double/floatto an integer type round instead of truncatingConvert.ToInt32(decimal)rounds midpoints away from zero, where .NET rounds them to even #4158Convert.ToInt32(decimal)rounds midpoints away from zero (thedoubleoverload agrees with .NET)(byte)casts don't wrap, becausebytemaps tosmallint#4159 unchecked(byte)casts don't wrapBigIntegerdivision is BigInteger division returns fractional results instead of integer division #4143 (@Zentauer, with Translate BigInteger division to div() #4144)The others kept their first bug and point to the new issues:
LocalDateTime.InZoneLeniently(zone).ToInstant()resolves an ambiguous local time to the later instant #4085 → NodaTime: date parts ofLocalDateTime.InZoneLeniently(zone)are read in the session time zone, not inzone#4145, NodaTime:Instant.InZone(zone).ToInstant()appliesAT TIME ZONEto the instant instead of returning it #4146TimeSpan/Durationconstants with a day part become the wrongINTERVALliteral, also inHasDataandHasDefaultValue#4086 →floatconstants are inlined without a type, sor.Single == 0.1fnever matches #4147 (the interval part stays in NegativeTimeSpan/Durationconstants with a day part become the wrongINTERVALliteral, also inHasDataandHasDefaultValue#4086)DateTime.Secondrounds the fraction, so 23:59:59.999 gives 60 #4090 →TimeOnly - TimeOnlyreturns a negative interval instead of wrapping around midnight #4148,(DateTime?)DateTimeOffset.DateTimeis shifted by the session time zone #4149 (IsBetweenwas already TimeOnly.IsBetween returns incorrect results for ranges spanning midnight #4129)EqualsExact(g, tolerance)drops the tolerance #4092 → NTS:Buffer(distance, EndCapStyle)passes the cap style asST_Buffer'squad_segsargument #4150 to NTS:EnvelopeCombiner.CombineAsGeometryloses the SRID #4154Regex.Replacepasses .NET substitutions through toregexp_replace, where they mean something else #4094 → Regex:RegexOptions.Singleline | RegexOptions.Multilinerenders thenflag, so.doesn't match a newline #4155, Regex: under the defaultpflag a negated bracket like[^x]never matches a newline #4156charspace is lost when it becomes text:string.Join,PadLeft/PadRightandchar.ToString()#4096 →Convert.ToString(bool)returnstrue/false, where .NET returnsTrue/False#4160,string.Joinwith a null separator returns NULL instead of joining without one #4161I left #4083, #4087, #4088, #4091, #4093, #4097 and #4099 as they are, since each has one root cause and one fix (#4116 fixes #4087 and both halves of #4088 in one change). If you'd rather have any of those split too, tell me and I'll do it.
roji commentedon Nov 25, 2026
Thanks @CaffeinatedCoder, much appreciated.