using Microsoft.SqlServer.Types; using System; using System.Data; using System.Data.Entity.Spatial; using System.Data.SqlClient; using System.Data.SqlTypes; namespace Dapper.EntityFramework { /// /// Type-handler for the DbGeography spatial type /// public class DbGeographyHandler : Dapper.SqlMapper.TypeHandler { /// /// Create a new handler instance /// protected DbGeographyHandler() { } /// /// Default handler instance /// public static readonly DbGeographyHandler Default = new DbGeographyHandler(); /// /// Assign the value of a parameter before a command executes /// /// The parameter to configure /// Parameter value public override void SetValue(IDbDataParameter parameter, DbGeography value) { object parsed = null; if (value != null) { parsed = SqlGeography.STGeomFromWKB(new SqlBytes(value.AsBinary()), value.CoordinateSystemId); } parameter.Value = parsed ?? DBNull.Value; if (parameter is SqlParameter) { ((SqlParameter)parameter).UdtTypeName = "geography"; } } /// /// Parse a database value back to a typed value /// /// The value from the database /// The typed value public override DbGeography Parse(object value) { if (value == null || value is DBNull) return null; if (value is SqlGeography) { var geo = (SqlGeography)value; return DbGeography.FromBinary(geo.STAsBinary().Value); } return DbGeography.FromText(value.ToString()); } } }