Skip to content

NetTopologySuite

Weasel.Postgresql includes built-in support for spatial types via NetTopologySuite and the PostGIS extension.

Prerequisites

Ensure PostGIS is installed in your database and the Npgsql NetTopologySuite plugin is configured:

bash
dotnet add package Npgsql.NetTopologySuite
dotnet add package Weasel.Postgresql

Enable the PostGIS extension in your database schema:

cs
yield return new Extension("postgis");

snippet source | anchor

NpgsqlDataSource Configuration

Register the NetTopologySuite type mappings when building your data source:

cs
var builder = new NpgsqlDataSourceBuilder("Host=localhost;Database=myapp;");
builder.UseNetTopologySuite();
await using var dataSource = builder.Build();

snippet source | anchor

Type Mappings

Weasel automatically maps NetTopologySuite.Geometries.Geometry (and its subclasses) to the PostgreSQL geometry type. This mapping is included in the default NpgsqlTypeMapper.

.NET TypePostgreSQL Type
Geometrygeometry
Pointgeometry
LineStringgeometry
Polygongeometry
MultiPointgeometry
MultiLineStringgeometry
MultiPolygongeometry
GeometryCollectiongeometry

Using Spatial Columns

Define geometry columns on your tables:

cs
var table = new Table("locations");
table.AddColumn<int>("id").AsPrimaryKey();
table.AddColumn<string>("name").NotNull();
table.AddColumn<Geometry>("geom");

snippet source | anchor

This generates a column of type geometry. For more specific PostGIS types, use the string overload:

cs
var table = new Table("locations");
table.AddColumn("geom", "geometry(Point, 4326)");

snippet source | anchor

Spatial Indexes

Create a GiST index for spatial queries:

cs
var table = new Table("locations");

var index = new IndexDefinition("idx_locations_geom")
{
    Method = IndexMethod.gist
};
index.Columns = new[] { "geom" };
table.Indexes.Add(index);

snippet source | anchor

This generates:

sql
CREATE INDEX idx_locations_geom ON public.locations USING gist (geom);

Released under the MIT License.