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 : SqlMapper.TypeHandler
{
///
/// Create a new handler instance.
///
protected DbGeographyHandler() { /* create new */ }
///
/// 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 is not null)
{
parsed = SqlGeography.STGeomFromWKB(new SqlBytes(value.AsBinary()), value.CoordinateSystemId);
}
parameter.Value = parsed ?? DBNull.Value;
if (parameter is SqlParameter sqlParameter)
{
sqlParameter.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 is null || value is DBNull) return null;
if (value is SqlGeography geo)
{
return DbGeography.FromBinary(geo.STAsBinary().Value, geo.STSrid.Value);
}
return DbGeography.FromText(value.ToString());
}
}
}