Dan*_*Dan 8 c# type-conversion dapper
SqlMapper.Query<T> 似乎忽略了我的注册 TypeHandler<T>
这是一个简单的查询:
SELECT 'Foo' AS CategoryName, 200 AS CategoryRating
Run Code Online (Sandbox Code Playgroud)
......这里有两个POCO:
public class RatingValue
{
public Int32 Value { get; set; }
// ... some other properties etc ...
}
public class MyResult
{
public String CategoryName { get; set; }
public RatingValue CategoryRating { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我已经创建了一个新的TypeHandler实现,它应该将CategoryRating Int32转换为一个RatingValue对象:
public class RatingValueHandler: SqlMapper.TypeHandler<RatingValue>
{
public override RatingValue Parse(object value)
{
if (value is Int32)
return new RatingValue() { Value = (Int32)value };
throw new FormatException("Invalid conversion to RatingValue");
}
public override void SetValue(System.Data.IDbDataParameter parameter, RatingValue value)
{
// ... null, range checks etc ...
parameter.DbType = System.Data.DbType.Int32;
parameter.Value = Int32.Parse(value.Value);
}
}
Run Code Online (Sandbox Code Playgroud)
现在,在运行我的查询之前,我正在添加我的新处理程序,如下所示:
SqlMapper.AddTypeHandler<RatingValue>(new RatingValueHandler());
Run Code Online (Sandbox Code Playgroud)
但是,当我运行这个时:
c.Query<MyResult>("SELECT 'Foo' AS CategoryName, 200 AS CategoryRating");
Run Code Online (Sandbox Code Playgroud)
我从Dapper得到一个例外 - 它无法解析第1列中的结果.我期望 Dapper解雇我的自定义类型处理程序!
我想我错过了非常非常明显的事情.请告诉我,我有多傻!
你是不是很傻; 是我; 以下现在在本地传递(推送到github); 将部署到的NuGet很快 现在市面上的NuGet在v1.27以上:
public void SO24740733_TestCustomValueHandler()
{
Dapper.SqlMapper.AddTypeHandler(RatingValueHandler.Default);
var foo = connection.Query<MyResult>(
"SELECT 'Foo' AS CategoryName, 200 AS CategoryRating").Single();
foo.CategoryName.IsEqualTo("Foo");
foo.CategoryRating.Value.IsEqualTo(200);
}
public void SO24740733_TestCustomValueSingleColumn()
{
Dapper.SqlMapper.AddTypeHandler(RatingValueHandler.Default);
var foo = connection.Query<RatingValue>(
"SELECT 200 AS CategoryRating").Single();
foo.Value.IsEqualTo(200);
}
Run Code Online (Sandbox Code Playgroud)