Using Dapper with SQL Spatial Types as a parameter

做~自己de王妃 提交于 2019-11-28 07:46:51
Sam Saffron

The key to implementing weird and wonderful DB specific params all boils down to SqlMapper.IDynamicParameters

This simple interface has a single endpoint:

public interface IDynamicParameters
{
    void AddParameters(IDbCommand command);
}

Dapper already has a DB generic implementation of this interface called: DynamicParameters which allows you to handle output and return values.

To emulate this spatial stuff I would try something like:

public class SpatialParam : SqlMapper.IDynamicParameters
{
    string name; 
    object val;

    public SpatialParam(string name, object val)
    {
       this.name = name; 
       this.val = val;
    }

    public void AddParameters(IDbCommand command, SqlMapper.Identity identity)
    {
       var sqlCommand = (SqlCommand)command;
       sqlCommand.Parameters.Add(new SqlParameter
       {
          UdtTypeName = "geometry",
          Value = val,
          ParameterName = name
       });
    }
}

Usage:

cnn.Query("SELECT * FROM MyTable WHERE @parameter.STIntersects(MyGeometryColumn)",
  new SpatialParam("@parameter", builder.ConstructedGeometry));

This simple implementation of the interface handles only a single param, but it can easily be extended to handle multiple params, either by passing in from the constructor or adding a helper AddParameter method.

If you don't mind modifying Dapper at its core then you can use what I've done... https://gist.github.com/brendanmckenzie/4961483

I modified Dapper to accept Microsoft.SqlServer.Types.SqlGeography parameters.

  • Dapper.EntityFramework 1.26 has support for DbGeography
  • Dapper 1.32 has inbuilt support for SqlGeography
  • Dapper 1.33 has inbuilt support for SqlGeometry
  • Dapper.EntityFramework 1.33 has inbuilt support for DbGeometry
  • Dapper 1.34 has inbuilt support for SqlHierarchyId

So with the latest libraries; it should simply work.

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