How to use Dapper with MS SQL Server (2012) Geospatial / SQLGeography Column

丶灬走出姿态 提交于 2019-12-01 02:24:00

问题


I have a SQL Server 2012 database with a table that contains a geography column and I want to use Dapper in a .Net application working with that database, but as far as I can tell and see in the Dapper code, "only" Entity Framework's DBGeography type is supported, the underlying SQLGeography data type has no other mentioning in the repository.

Can Dapper handle these column types 'magically' nevertheless or would I have to explicitly write a Dapper.SqlMapper.TypeHandler for these?


回答1:


Support for SqlGeography has been added in the next release, again via the Dapper.EntityFramework package. I haven't built/deployed yet, as I am in two minds as to whether that is the most appropriate assembly for it to live in... but I also don't want to take a dependency on Microsoft.SqlServer.Types in the core library. There may be a way of doing it without that, though.


Update: this has now moved up a level to the core library, so you shouldn't need any EF references or Dapper.EntityFramework; it should just work; this has been pushed as Dapper 1.32.

Example:

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; }
}


来源:https://stackoverflow.com/questions/25538154/how-to-use-dapper-with-ms-sql-server-2012-geospatial-sqlgeography-column

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