From 698e308c795ef89886f80eed9374e3bdcf50fb0c Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Mon, 4 May 2026 16:38:24 +0200 Subject: [PATCH] Fix ST_Extent box2d cast being removed by EF simplifier ST_Extent returns box2d in PostgreSQL, but the aggregate expression was assigned the geometry type mapping. EF's SqlExpressionSimplifyingExpressionVisitor then stripped the ::geometry cast as a no-op (same store type), leaving the raw box2d result which has no binary output function. Fix by giving the aggregate a box2d store type so the cast is recognized as a real type conversion. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- ...etTopologySuiteAggregateMethodCallTranslatorPlugin.cs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/EFCore.PG.NTS/Query/ExpressionTranslators/Internal/NpgsqlNetTopologySuiteAggregateMethodCallTranslatorPlugin.cs b/src/EFCore.PG.NTS/Query/ExpressionTranslators/Internal/NpgsqlNetTopologySuiteAggregateMethodCallTranslatorPlugin.cs index 86de97978..c1d912c2c 100644 --- a/src/EFCore.PG.NTS/Query/ExpressionTranslators/Internal/NpgsqlNetTopologySuiteAggregateMethodCallTranslatorPlugin.cs +++ b/src/EFCore.PG.NTS/Query/ExpressionTranslators/Internal/NpgsqlNetTopologySuiteAggregateMethodCallTranslatorPlugin.cs @@ -122,7 +122,10 @@ public NpgsqlNetTopologySuiteAggregateMethodTranslator( if (method == EnvelopeCombineMethod) { // ST_Extent returns a PostGIS box2d, which isn't a geometry and has no binary output function. - // Convert it to a geometry first. + // We need to cast the result to geometry. The aggregate function must use 'box2d' as the store type + // so that the cast to geometry is not stripped as a no-op by EF's SqlExpressionSimplifyingExpressionVisitor. + var geometryMapping = GetMapping(); + return _sqlExpressionFactory.Convert( _sqlExpressionFactory.AggregateFunction( "ST_Extent", @@ -131,8 +134,8 @@ public NpgsqlNetTopologySuiteAggregateMethodTranslator( nullable: true, argumentsPropagateNullability: [false], typeof(Geometry), - GetMapping()), - typeof(Geometry), GetMapping()); + geometryMapping?.WithStoreTypeAndSize("box2d", null)), + typeof(Geometry), geometryMapping); } if (method == UnionMethod || method == GeometryCombineMethod)