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.PostgresqlEnable the PostGIS extension in your database schema:
cs
yield return new Extension("postgis");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();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 Type | PostgreSQL Type |
|---|---|
Geometry | geometry |
Point | geometry |
LineString | geometry |
Polygon | geometry |
MultiPoint | geometry |
MultiLineString | geometry |
MultiPolygon | geometry |
GeometryCollection | geometry |
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");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)");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);This generates:
sql
CREATE INDEX idx_locations_geom ON public.locations USING gist (geom);