Fluent NHibernate automap PostGIS geometry type
Given the following model:
using NetTopologySuite.Geometries;
public class bounding_box
{
public virtual int id { get; protected set; }
public virtual Polygon area { get; set; }
}
How do I automate a property area
on a column area geometry(Polygon)
when creating a DB schema using Fluent Nhibernate? Please note that I do not need to read / update the geometry column with NHibernate as I will be using GDAL in my code.
I know I can do this by doing a manual override, i.e .:
public class bounding_boxMappingOverrride : IAutoMappingOverride<bounding_box>
{
public void Override(AutoMapping<bounding_box> mapping)
{
mapping.Map(x => x.area)
.CustomSqlType("geometry(Polygon)");
}
}
However, I have a lot of tables with geometers, so I would prefer to be able to specify a custom type mapping.
For some reason, the property is area
never intercepted by the following property agreement:
public class PostgisTypesConvention : IPropertyConvention
{
public void Apply(IPropertyInstance instance)
{
if (instance.Type == typeof(Polygon))
{
instance.CustomSqlType("geometry(Polygon)"); // Never reached
}
}
}
I have the same problem if I use GeoAPI.Geometries.IPolygon
instead NetTopologySuite.Geometries.Polygon
...
source to share
Finally, I was able to solve this problem by specifying a custom UserTypeConvention
, i.e.
using NetTopologySuite.Geometries;
using NHibernate.Spatial.Type;
public class PostGisPolygonUserTypeConvention : UserTypeConvention<PostGisGeometryType>
{
public override void Accept(IAcceptanceCriteria<IPropertyInspector> criteria)
{
criteria.Expect(c => c.Type == typeof(Polygon));
}
public override void Apply(IPropertyInstance instance)
{
// Have to set CustomType to be able to read/write rows using NHibernate
instance.CustomType<PostGisGeometryType>();
// Have to set CustomSqlType to generate correct SQL schema
instance.CustomSqlType("geometry(Polygon)");
}
}
The same principle can also be used to generate UserTypeConventions
other geometries, such as Point
, LineString
, MultiPoint
, etc.
source to share