使用Dapper调用带有地理位置参数的PostgreSQL函数时出现NotSupportedException

时间:2018-07-07 18:15:29

标签: c# postgresql dapper npgsql nettopologysuite

我正在使用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

2 个答案:

答案 0 :(得分:2)

进行搜索后,我发现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());,一切正常。

答案 1 :(得分:0)

如果您刚刚升级到Npgsql 4,则需要使用空间插件之一。阅读[发行说明](http://www.npgsql.org/doc/release-notes/4.0.html#improved-spatial-support-postgis)。