我在Postgresql中有一个空间数据。例如,表格planet_osm_point具有2个属性:
CREATE TABLE public.planet_osm_point
(
osm_id bigint,
way geometry(Point,3857)
)
如果我使用dapper进行CRUD操作,则一切正常。但是,如果我使用Dapper.fastCRUD,则带有几何图形的“ way”属性始终为空
OsmPoint类:
using NetTopologySuite.Geometries;
using System.ComponentModel.DataAnnotations.Schema;
namespace DapperTest
{
[Table("planet_osm_point")]
public class OsmPoint
{
[Column("osm_id")]
public long OsmId { get; set; }
[Column("way")]
public Point Way { get; set; }
}
}
如果我使用Dapper,那么我会收到Way属性具有几何坐标:
using (NpgsqlConnection conn = new NpgsqlConnection(_connectionString))
{
conn.Open();
conn.TypeMapper.UseNetTopologySuite();
var result = conn.Query<OsmPoint>("SELECT * FROM planet_osm_point LIMIT 5000").ToList();
return result;
}
但是如果我使用Dapper.fastCRUD,则Way始终为空
using (NpgsqlConnection conn = new NpgsqlConnection(_connectionString))
{
conn.Open();
conn.TypeMapper.UseNetTopologySuite();
var result = conn.Find<OsmPoint>(p=>p.Top(5000));
return result;
}
有人知道如何使Dapper.fastCRUD处理几何数据吗?
答案 0 :(得分:0)
首先,您要为Geometry类型创建TypeHandler,如下所示:
public class GeometryTypeMapper : SqlMapper.TypeHandler<Geometry>
{
public override void SetValue(IDbDataParameter parameter, Geometry value)
{
if (parameter is NpgsqlParameter npgsqlParameter)
{
npgsqlParameter.NpgsqlDbType = NpgsqlDbType.Geometry;
npgsqlParameter.NpgsqlValue = value;
}
else
{
throw new ArgumentException();
}
}
public override Geometry Parse(object value)
{
if (value is Geometry geometry)
{
return geometry;
}
throw new ArgumentException();
}
}
添加类型处理程序:
SqlMapper.AddTypeHandler(new GeometryTypeMapper());
在FastCURD查询之前设置属性:
OrmConfiguration.GetDefaultEntityMapping<OsmPoint>().SetProperty(p => p.way, prop => prop.SetDatabaseColumnName("way"));
答案 1 :(得分:0)
Dapper.FastCRUD作为默认值仅使用对称SQL类型来构建查询。 您可以在Dapper.FastCrud.Configuration.OrmConventions.cs中看到它:
public virtual IEnumerable<PropertyDescriptor> GetEntityProperties(Type entityType)
{
return TypeDescriptor.GetProperties(entityType)
.OfType<PropertyDescriptor>()
.Where(propDesc =>
!propDesc.Attributes.OfType<NotMappedAttribute>().Any()
&& !propDesc.IsReadOnly
&& propDesc.Attributes.OfType<EditableAttribute>().All(editableAttr => editableAttr.AllowEdit)
&& this.IsSimpleSqlType(propDesc.PropertyType));
}
我重写IsSimpleSqlType(Type propertyType)方法:
public class GeometryConvention: OrmConventions
{
protected override bool IsSimpleSqlType(Type propertyType)
{
var res = base.IsSimpleSqlType(propertyType) || propertyType.BaseType != null && propertyType.BaseType.Name.StartsWith("geometry", StringComparison.OrdinalIgnoreCase);
return res;
}
}
注册自定义约定:
OrmConfiguration.Conventions = new GeometryConvention();
并使用自定义的GeometryTypeMapper,例如在LongNgôThành答案中。