什么原因会导致Dapper转换失败?

6

我正在使用Dapper执行一个非常简单的查询:

const string query =
          "SELECT measurement From Table;";
return connection.Query<Foo>(query);

假设有如下定义的foo

public class Foo
{
    public object measurement { get; set; }
}

它完美地工作。如果我检查结果对象,Measurement 是一个 double

然而,如果我明确将 Measurement 类型指定为 double

public class Foo
{
    public double measurement { get; set; }
}

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);
                }
            }

编辑2:无论是堆栈跟踪

Dapper.SqlMapper.ThrowDataException(Exception ex, Int32 index, IDataReader reader, Object value)

还是内部异常

System.InvalidCastException /“指定的转换无效”

都不是很有用。


8
数据库中的“measurement”是否可为空? - haim770
数据库中该列的数据类型是什么? - Zohar Peled
你可以尝试使用 float? 代替 double - D-Shih
显示堆栈跟踪和内部异常(如果存在) - haim770
1
对不起,在Microsoft Docs的Oracle数据类型映射页面中找不到REAL。我猜它可能是floatdecimal,或者只是一个丑陋的双重转换 - (double)(object)。我想知道你是否遇到了一个错误。 - Zohar Peled
显示剩余8条评论
1个回答

0
感谢 @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;
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接