我正在使用Dapper执行一个非常简单的查询:
const string query =
"SELECT measurement From Table;";
return connection.Query<Foo>(query);
Run Code Online (Sandbox Code Playgroud)
与foo定义如下:
public class Foo
{
public object measurement { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
它完美地运作.如果我检查结果对象,Measurement是一个double.
不过,如果我明确地键入Measurement一个double:
public class Foo
{
public double measurement { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
Dapper抛出异常:
System.Data.DataException:'解析第0列时出错(measurement = 4.64518928527832 - Double)'
由于作为对象输入有效,它并不太烦人,但我想了解导致这种行为的原因.
编辑:做同样的事情,老式的方式非常好用measurement打字作为一个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);
}
}
Run Code Online (Sandbox Code Playgroud)
Edit2:堆栈跟踪都没有
Dapper.SqlMapper.ThrowDataException(Exception ex,Int32 index,IDataReader reader,Object value)
也不是内在的例外
System.InvalidCastException /"指定的强制转换无效"
非常有用.
感谢@haim770,我已经能够使用最简单的 TypeHandler 来解决这个问题:
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;
}
}
Run Code Online (Sandbox Code Playgroud)