如何在MS SQL Server(2012)Geospatial/SQLGeography Column中使用Dapper

Jör*_*ann 6 sql sql-server dapper

我有一个SQL Server 2012数据库,其中包含一个包含地理列的表,我想在使用该数据库的.Net应用程序中使用Dapper,但据我所知,在Dapper代码中看到"仅"实体框架支持 DBGeography类型,底层SQLGeography数据类型在存储库中没有其他提及.

Dapper可以"神奇地"处理这些列类型,还是我必须为这些列显式写一个Dapper.SqlMapper.TypeHandler?

Mar*_*ell 7

SqlGeography已经在下一个版本中再次通过Dapper.EntityFramework软件包添加了支持.我还没有构建/部署,因为我有两种想法,认为这是否是最适合它的组件......但我也不想依赖于Microsoft.SqlServer.Types核心库.不过,可能有一种方法可以做到这一点.


更新:现在已经升级到核心库,因此您不需要任何EF引用或Dapper.EntityFramework; 它应该工作 ; 这被推到了Dapper 1.32.

例:

public void SqlGeography_SO25538154()
{
    Dapper.SqlMapper.ResetTypeHandlers(); // to show it doesn't depend on any
    connection.Execute("create table #SqlGeo (id int, geo geography)");

    var obj = new HazSqlGeo
    {
        Id = 1,
        Geo = SqlGeography.STLineFromText(
            new SqlChars(new SqlString(
                "LINESTRING(-122.360 47.656, -122.343 47.656 )")), 4326)
    };
    connection.Execute("insert #SqlGeo(id, geo) values (@Id, @Geo)", obj);
    var row = connection.Query<HazSqlGeo>(
        "select * from #SqlGeo where id=1").SingleOrDefault();
    row.IsNotNull();
    row.Id.IsEqualTo(1);
    row.Geo.IsNotNull();
}

class HazSqlGeo
{
    public int Id { get; set; }
    public SqlGeography Geo { get; set; }
}
Run Code Online (Sandbox Code Playgroud)