I am using Dapper to execute a very simple query:
const string query =
"SELECT measurement From Table;";
return connection.Query<Foo>(query);
with foo
defined as follows:
public class Foo
{
public object measurement { get; set; }
}
It works perfectly. If I inspect the resulting object, Measurement
is a double
.
However, if I explicitely type Measurement
as a double
:
public class Foo
{
public double measurement { get; set; }
}
Dapper throws an exception:
System.Data.DataException: 'Error parsing column 0 (measurement=4.64518928527832 - Double)'
Since typing as object works, it is not too annoying, but I would like to understand what causes this behavior.
Edit: Doing the same thing the old-fashionned way works perfectly fine with measurement
typed as a Double
using (connection)
{
connection.Open();
var cmd = connection.CreateCommand();
cmd.CommandText = "SELECT measurement From Table;";
Foo foo= new Foo();
using (IDataReader reader = cmd.ExecuteReader())
{
reader.Read();
foo.measurement = reader.GetDouble(0);
}
}
Edit2: Neither the stack trace
Dapper.SqlMapper.ThrowDataException(Exception ex, Int32 index, IDataReader reader, Object value)
nor the inner exception
System.InvalidCastException / "The specified cast is invalid"
are very useful.
Thanks to @haim770, I have been able to work around the issue, using the simplest TypeHandler possible:
public class DoubleTypeHandler : SqlMapper.TypeHandler<double>
{
public override void SetValue(IDbDataParameter parameter, double value)
{
throw new NotImplementedException();
}
public override double Parse(object value)
{
return value;
}
}