当前位置:网站首页>如何让 Dapper 支持 DateOnly 类型
如何让 Dapper 支持 DateOnly 类型
2022-06-29 12:36:00 【dotNET跨平台】
前言
在上次的文章中,我们让 EF Core 6 支持了 DateOnly 类型。
那么,Dapper 是否支持 DateOnly 类型呢?
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public DateOnly Birthday { get; set; }
}
using (var connection = new SqlConnection(connectionString))
{
var users = connection.Query<User>("select * from users");
}也不行:

由于异常提示没有任何指导意义,于是我们想从源码入手解决。
深入探究
调用堆栈
通过调用堆栈,找到发生异常的位置位于SqlMapper.cs第 1113 行:

第 1113 行具体代码如下:

其中func的来源是tuple.Func,而 tuple 是通过如下方式赋值的:
tuple = info.Deserializer = new DeserializerState(hash, GetDeserializer(effectiveType, reader, 0, -1, false));看到Deserializer这个单词,立刻引起了我们的注意:序列化
GetDeserializer 方法
赶紧来看看GetDeserializer方法的实现:
private static Func<IDataReader, object> GetDeserializer(Type type, IDataReader reader, int startBound, int length, bool returnNullIfFirstMissing)
{
// dynamic is passed in as Object ... by c# design
if (type == typeof(object) || type == typeof(DapperRow))
{
return GetDapperRowDeserializer(reader, startBound, length, returnNullIfFirstMissing);
}
Type underlyingType = null;
if (!(typeMap.ContainsKey(type) || type.IsEnum || type.IsArray || type.FullName == LinqBinary
|| (type.IsValueType && (underlyingType = Nullable.GetUnderlyingType(type)) != null && underlyingType.IsEnum)))
{
if (typeHandlers.TryGetValue(type, out ITypeHandler handler))
{
return GetHandlerDeserializer(handler, type, startBound);
}
return GetTypeDeserializer(type, reader, startBound, length, returnNullIfFirstMissing);
}
return GetStructDeserializer(type, underlyingType ?? type, startBound);
}方法会从 typeHandlers 中获取ITypeHandler接口的实现。
而ITypeHandler接口定义如下:
/// <summary>
/// Implement this interface to perform custom type-based parameter handling and value parsing
/// </summary>
public interface ITypeHandler
{
/// <summary>
/// Assign the value of a parameter before a command executes
/// </summary>
/// <param name="parameter">The parameter to configure</param>
/// <param name="value">Parameter value</param>
void SetValue(IDbDataParameter parameter, object value);
/// <summary>
/// Parse a database value back to a typed value
/// </summary>
/// <param name="value">The value from the database</param>
/// <param name="destinationType">The type to parse to</param>
/// <returns>The typed value</returns>
object Parse(Type destinationType, object value);
}实现此接口以执行自定义的基于类型的参数处理和值解析
这不正是我们想要的吗?
AddTypeHandler 方法
而怎么向 Dapper 传入ITypeHandler实现呢?
我们最终找到了AddTypeHandler方法:
/// <summary>
/// Configure the specified type to be processed by a custom handler.
/// </summary>
/// <param name="type">The type to handle.</param>
/// <param name="handler">The handler to process the <paramref name="type"/>.</param>
public static void AddTypeHandler(Type type, ITypeHandler handler) => AddTypeHandlerImpl(type, handler, true);配置要由自定义处理程序处理的指定类型
实现
首先,创建ITypeHandler实现:
public class DateOnlyTypeHandler : TypeHandler<DateOnly>
{
public override DateOnly Parse(object value)
{
return DateOnly.FromDateTime((DateTime)value);
}
public override void SetValue(IDbDataParameter parameter, DateOnly value)
{
parameter.Value = value.ToDateTime(TimeOnly.MinValue);
}
}然后,在启动时添加自定义处理程序:
SqlMapper.AddTypeHandler<DateOnly>(new DateOnlyTypeHandler());现在,程序就可以正常运行了。
结论
今天,我们介绍了使用自定义ITypeHandler来告诉 Dapper 如何处理默认不支持的数据类型。
添加微信号【MyIO666】,邀你加入技术交流群
边栏推荐
- RT thread memory management
- Qitai observation: professional elites must step on the huge pit of entrepreneurship - learning effect pit
- Cvpr2022 | panopticdepth: a unified framework for depth aware panoramic segmentation
- 维修记录导出的excel表格太大怎么办?
- MySQL常用语句和命令汇总
- Precautions for Beifu controller connecting Panasonic EtherCAT servo
- Is it safe to open an account online?
- 存算一体为何是造芯新方向?|对撞派 x 知存科技
- 服务器监控netdata面板配置邮件服务
- @Table爆红
猜你喜欢

C语言内存函数

Exploring the way of automated testing - Preparation

力扣:合并两个有序链表

Cvpr2022 𞓜 thin domain adaptation

Evaluation of powerful and excellent document management software: image management, book management and document management

Huawei machine learning service speech recognition function enables applications to paint "sound" and color

STK_GLTF模型

3D model downloading and animation control

别再重复造轮子了,推荐使用 Google Guava 开源工具类库,真心强大!

Tutorial on building pytoch model from zero (IV) compiling training process -- Parameter Analysis
随机推荐
Rslo: self supervised lidar odometer (real time + high precision, icra2022)
Huawei machine learning service speech recognition function enables applications to paint "sound" and color
SCHIEDERWERK電源維修SMPS12/50 PFC3800解析
开户可以在网上开么?能安全吗
360数科新能源专项产品规模突破60亿
Learn from the official motor and BLDC control strategies, and make money as soon as you learn
从零搭建Pytorch模型教程(五)编写训练过程--一些基本的配置
C # implements definition, insertion and construction of binary sort tree
Cvpr2022 𞓜 future transformer with long-term action expectation
Gee - American landfire fire fire data set
Application Service Vulnerability scanning and exploitation of network security skills competition in secondary vocational schools (SSH private key disclosure)
成功解决ValueError: Only TF native optimizers are supported in Eager mode
Cvpr2022 | panopticdepth: a unified framework for depth aware panoramic segmentation
从零搭建Pytorch模型教程(四)编写训练过程--参数解析
存算一体为何是造芯新方向?|对撞派 x 知存科技
Code tidiness learning notes
Another "provincial capital university", coming!
Mirror vulnerability scanner: trivy
Shell judges whether the command is executed successfully
The role of each part of Neural Network & thoroughly understand neural network