我正在使用Dapper(使用带有npgsql
插件的NetTopologySuite
数据提供程序)使用geography
参数调用PostgreSQL函数,然后收到NotSupportedException
:
System.NotSupportedException: The member _location of type NetTopologySuite.Geometries.Point cannot be used as a parameter value
at Dapper.SqlMapper.LookupDbType(Type type, String name, Boolean demand, ITypeHandler& handler) in C:\projects\dapper\Dapper\SqlMapper.cs:line 417
at Dapper.SqlMapper.CreateParamInfoGenerator(Identity identity, Boolean checkForDuplicates, Boolean removeUnused, IList`1 literals) in C:\projects\dapper\Dapper\SqlMapper.cs:line 2516
at Dapper.SqlMapper.GetCacheInfo(Identity identity, Object exampleParameters, Boolean addToCache) in C:\projects\dapper\Dapper\SqlMapper.cs:line 1707
at Dapper.SqlMapper.ExecuteScalarImplAsync[T](IDbConnection cnn, CommandDefinition command) in C:\projects\dapper\Dapper\SqlMapper.Async.cs:line 1207
...
但是当我使用通过NpgsqlCommand
方法指定的类型的AddWithValue
时,它工作正常。
我怎样才能让Dapper将NetTopologySuite.Geometries.Point
映射到geography
?
在做了一些搜索后,我发现了一个unaccepted answer解决了我的问题。
确保我添加了Npgsql.NetTopologySuite包并且其映射器已启用connection.TypeMapper.UseNetTopologySuite();
然后ADO.Net命令正常工作。
我添加了一个自定义Dapper.SqlMapper.TypeHandler
:
public class GeographyTypeMapper : SqlMapper.TypeHandler<Geometry> {
public override void SetValue(IDbDataParameter parameter, Geometry value) {
if (parameter is NpgsqlParameter npgsqlParameter) {
npgsqlParameter.NpgsqlDbType = NpgsqlDbType.Geography;
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 GeographyTypeMapper());
,一切正常。
我刚刚升级到Npgsql 4,你需要使用其中一个空间插件。阅读[发行说明](http://www.npgsql.org/doc/release-notes/4.0.html#improved-spatial-support-postgis)。