gpt4 book ai didi

c# - 什么会导致 Dapper cast 失败?

转载 作者:太空狗 更新时间:2023-10-29 23:49:16 24 4
gpt4 key购买 nike

我正在使用 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: 'Error parsing column 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);
}
}

Edit2:既不是堆栈跟踪

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

也不是内部异常

System.InvalidCastException / "The specified cast is invalid"

非常有用。

最佳答案

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

关于c# - 什么会导致 Dapper cast 失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51267061/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com