Fluent NHibernate automap PostGIS geometry type

巧了我就是萌 提交于 2019-12-10 17:48:14

问题


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 automap the area property to a area geometry(Polygon) column when generating the DB schema using Fluent Nhibernate? Note that I do not care about being able to read / update the geometry column using NHibernate since I will be using GDAL in my code.

I know I can do it by implementing 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 many tables with geometry columns so I would much prefer to be able to specify a custom type mapping.

For some reason, the area property is never intercepted by the following property convention:

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 of NetTopologySuite.Geometries.Polygon...


回答1:


I was finally able to resolve this by defining 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 create UserTypeConventions for other geometries, such as Point, LineString, MultiPoint, etc.



来源:https://stackoverflow.com/questions/29939528/fluent-nhibernate-automap-postgis-geometry-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!