背景
开发GIS系统后台服务时常常需要调用PostGIS空间数据库进行空间查询,分析;
Dapper过于轻量。虽然能减少一些类型转换的代码量,但在系统稍有规模时,频繁编写、调试SQL的开发效率过低;
EntityFramework过重,支持翻译为PostGIS调用的空间操作比较少。
LINQ2db轻重程度介于Dapper于EntityFramework之间,且空间扩展支持的空间函数较为全面,在遇到性能要求比较高,SQL控制粒度较细的场合,也支持直接调用SQL。
因此选择LINQ2db作为GIS系统的ORM。
使用
环境
PostGIS 3.x
dotnet standard2及以上
启用PostGIS空间扩展:
create extension postgis;
创建表格:
CREATE TABLE pois
(
id integer primary key,
prop1 varchar not null,
geom geometry(POINT,4326) not null
);
CREATE TABLE regions
(
id integer primary key,
prop1 varchar not null,
geom geometry(POLYGON,4326) not null
);
CREATE TABLE roads
(
id integer primary key,
prop1 varchar not null,
geom geometry(LINESTRING,4326) not null
);
安装
dotnet add package LinqToDBPostGisNTS --version 0.0.4
调用
MODEL
[Table("pois", Schema = "public")]
public class MyPOI
{
[Column("id")]
public int Id;
[Column("prop1")]
public string Prop1;
[Column("geom")]
public Geometry Geom;
}
[Table("roads",Schema = "public"]
public class Road
{
[Column("id")]
public int id;
[Column("prop1")]
public string Prop;
[Column("geom")]
public Geometry Geom;
}
[Table("regions",Schema = "public")]
public class Region
{
[Column("id")]
public int Id;
[Column("prop1")]
public string Prop;
[Column("geom")]
public Geometry Geom;
}
dbcontext
public class MyDBContext : DataConnection
{
public MyDBContext(string providerName, string connectionString)
: base(providerName, connectionString)
{
}
public ITable POIS{get{return GetTable();}}
}
using LinqToDB;
using (var db = new MyDBContext ("这里填写POSTGRESQL的连接字符串"))
{
const string wkt = "POINT(1 1)";
//查询空间上最近的兴趣点
var nearestPOI = db.POIS
.OrderBy(p => p.Geometry.STDistance(GeometryInput.STGeomFromText(WKT)))
.FirstOrDefault();
}