Skip to content

NTS: Geometry.Length of a polygon translates to ST_Length, which returns 0 #4151

Description

@CaffeinatedCoder
Environment
PostgreSQL 18.6 with PostGIS 3.6.4 (postgis/postgis:18-3.6), session TimeZone Etc/UTC
.NET 10 runtime 10.0.15, Npgsql.EntityFrameworkCore.PostgreSQL.NetTopologySuite 10.0.4, EF Core 10.0.15, Npgsql 10.0.4
.NET 11 runtime 11.0.0, Npgsql.EntityFrameworkCore.PostgreSQL.NetTopologySuite 11.0.0, EF Core 11.0.0, Npgsql 11.0.0
Also NetTopologySuite 2.6.0, macOS arm64

Both lines print the same output. main at 9a76cd8 has the same code.

Split from #4092 at your request.

NTS's Length of a polygon is its perimeter (SQL Server's STLength agrees). PostGIS's ST_Length returns 0 for areal geometries.

LINQ Row .NET PostgreSQL SQL
r.Polygon.Length a 4×4 square 16 0 ST_Length(r."Polygon")
Repro
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System.Globalization;
using NetTopologySuite.Geometries;

CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
var f = new GeometryFactory(new PrecisionModel(), 4326);
await using var context = new TestContext();
await context.Database.EnsureDeletedAsync();
await context.Database.EnsureCreatedAsync();

context.Rows.Add(new Row { Polygon = f.CreatePolygon([new(0, 0), new(4, 0), new(4, 4), new(0, 4), new(0, 0)]) });
await context.SaveChangesAsync();
var row = await context.Rows.AsNoTracking().SingleAsync();

// NTS returns the perimeter of a polygon; ST_Length returns 0 for areal geometries
Console.WriteLine($"Polygon.Length: .NET {row.Polygon.Length}, database {await context.Rows.Select(r => r.Polygon.Length).SingleAsync()}");

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.UseNetTopologySuite())
            .LogTo(Console.WriteLine, LogLevel.Information)
            .EnableSensitiveDataLogging();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
        => modelBuilder.HasPostgresExtension("postgis");
}

public class Row
{
    public int Id { get; set; }
    public Polygon Polygon { get; set; }
}

Output, the same on both lines:

Polygon.Length: .NET 16, database 0

Length maps to ST_Length for every geometry (NpgsqlNetTopologySuiteMemberTranslatorPlugin.cs#L158). ST_Perimeter gives the NTS answer for polygons and multipolygons; for a mixed column, ST_Length(g) + ST_Perimeter(g) matches NTS for any geometry type, since each returns 0 for the types it doesn't measure.

Activity

  1. added theissue type on Nov 26, 2026
  2. roji commented on Nov 26, 2026

    @roji
    Member

    AI Triage

    The below is an AI-generated analysis and may contain inaccuracies.

    Confirmed: the Npgsql translator maps Polygon.Length to ST_Length, which returns 0 for a polygon; NTS returns its perimeter. The repro below returns 16 and 0, respectively. I set the issue type to Bug.

    Versions and regression: Reproduced with provider 9.0.4, 10.0.4 and 11.0.0 (EF Core 9.0.4, 10.0.15 and 11.0.0, respectively), on PostgreSQL 18.4/PostGIS 3.6.3. This is not a regression from 9.0.4 to 10.0.4; no earlier working version was identified. The same translation was already present in 2019.

    Provider scope: SQLite 10.0.15 with SpatiaLite 5.1.0 also returns 0 for the same polygon, but through its own independent GLength translation. This warrants a separate EF SQLite issue; it does not remove the Npgsql provider bug. I found no likely duplicate in dotnet/efcore. The SQL Server provider generates .STLength(), which is documented to return a polygon's perimeter; I did not execute against SQL Server.

    Fix tradeoff: For an expression reliably typed as Polygon or MultiPolygon, replacing ST_Length with ST_Perimeter keeps a single SQL function call; known line types can retain ST_Length. MultiPolygon inherits Length from GeometryCollection, so the expression's type matters, not just the member's declaring type. This alone would leave polygons held in a base Geometry expression unresolved.

    The proposed ST_Length(g) + ST_Perimeter(g) worked for the tested PostGIS geometry point, line, polygon, multipolygon and mixed/nested collections, but should not be applied blindly to geography: for a geography collection containing a line and a polygon, PostGIS 3.6.3 returned the complete length from both functions, so summing them doubled it.

    There is also measurable cost to a second call. In a small local microbenchmark of 200,000 simple geometries (serial scan, warm cache, JIT off; median of five runs), lines took 16.5 ms with ST_Length versus 23.1 ms with both functions; polygons took 16.5 ms with ST_Perimeter versus 26.4 ms with both. These numbers are illustrative, not a production estimate. A general solution for mixed Geometry values should weigh that cost and the geography behavior against the added SQL complexity.

    For a polygon stored as PostGIS geometry, r.Polygon.Boundary.Length is a workaround: it produces ST_Length(ST_Boundary(...)) and returned 16 in the repro. It does add another spatial function.

    minimal repro

    Run against a fresh PostGIS-capable database specified by Test__Npgsql__DefaultConnection, with the Npgsql NetTopologySuite provider package installed.

    using Microsoft.EntityFrameworkCore;
    using Microsoft.Extensions.Logging;
    using NetTopologySuite.Geometries;
    
    var factory = new GeometryFactory(new PrecisionModel(), 4326);
    await using var context = new TestContext();
    await context.Database.EnsureCreatedAsync();
    
    var polygon = factory.CreatePolygon([new(0, 0), new(4, 0), new(4, 4), new(0, 4), new(0, 0)]);
    context.Rows.Add(new Row { Polygon = polygon });
    await context.SaveChangesAsync();
    
    Console.WriteLine($"NTS: {polygon.Length}, PostgreSQL: {await context.Rows.Select(r => r.Polygon.Length).SingleAsync()}");
    
    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.UseNetTopologySuite())
                .LogTo(Console.WriteLine, LogLevel.Information);
    
        protected override void OnModelCreating(ModelBuilder modelBuilder)
            => modelBuilder.HasPostgresExtension("postgis");
    }
    
    public class Row
    {
        public int Id { get; set; }
        public Polygon Polygon { get; set; } = null!;
    }
  3. self-assigned this
    on Nov 26, 2026
  4. added this to the 11.0.1 milestone on Nov 26, 2026
  5. roji commented on Nov 26, 2026

    @roji
    Member
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

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions