使用dapper查询空间数据

Lee*_*ary 4 c# sql-server spatial dapper micro-orm

我发现了一些相关问题,但作者放弃了并继续使用存储过程来进行"映射".

这实际上是一个延续的问题在这里

模型

public class Store
{
    public int Id { get; private set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public DbGeography Location { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

查询

using (SqlConnection conn = SqlHelper.GetOpenConnection())
{
    const string sql = "Select * from Stores";
    return conn.Query<Store>(sql, new { Tenant_Id = tenantId });
}
Run Code Online (Sandbox Code Playgroud)

Dapper不了解空间数据,正如许多人所说的那样,作者最初并不打算支持供应商特定的实现.但是Query<T>很难找到扩展支持的文档

Mar*_*ell 7

我在这里对此进行了探索,以下测试通过:

class HazGeo
{
    public int Id { get;set; }
    public DbGeography Geo { get; set; }
}
public void DBGeography_SO24405645_SO24402424()
{
    global::Dapper.SqlMapper.AddTypeHandler(typeof(DbGeography), new GeographyMapper());
    connection.Execute("create table #Geo (id int, geo geography)");

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

class GeographyMapper : Dapper.SqlMapper.TypeHandler<DbGeography>
{
    public override void SetValue(IDbDataParameter parameter, DbGeography value)
    {
        parameter.Value = value == null ? (object)DBNull.Value : (object)SqlGeography.Parse(value.AsText());
        ((SqlParameter)parameter).UdtTypeName = "GEOGRAPHY";
    }
    public override DbGeography Parse(object value)
    {
        return (value == null || value is DBNull) ? null : DbGeography.FromText(value.ToString());
    }
}
Run Code Online (Sandbox Code Playgroud)

看起来很可行,但是我还没有点缀每一个并且还穿过它们.欢迎您在本地尝试该提交 - 我很乐意反馈.