How to use Dapper with MS SQL Server (2012) Geospa

2019-02-17 09:45发布

问题:

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