Dapper does not natively know how to work with DateOnly and TimeOnly but by using a class which implements SqlMapper.TypeHandler using DateOnly and TimeOnly is possible.
Add these classes to your project.
UsageCode:public class SqlDateOnlyTypeHandler : SqlMapper.TypeHandler<DateOnly> { public override void SetValue(IDbDataParameter parameter, DateOnly date) => parameter.Value = date.ToDateTime(new TimeOnly(0, 0)); public override DateOnly Parse(object value) => DateOnly.FromDateTime((DateTime)value); } public class SqlTimeOnlyTypeHandler : SqlMapper.TypeHandler<TimeOnly> { public override void SetValue(IDbDataParameter parameter, TimeOnly time) { parameter.Value = time.ToString(); } public override TimeOnly Parse(object value) => TimeOnly.FromTimeSpan((TimeSpan)value); }
To use either one, before interacting with data with Dapper call one or both, here its done in a class constructor.
Alternate, add the following NuGet package kp.Dapper.Handlers and in the GitHub repository there are samples.Code:public DapperOperations() { SqlMapper.AddTypeHandler(new SqlDateOnlyTypeHandler()); SqlMapper.AddTypeHandler(new SqlTimeOnlyTypeHandler()); }
Tested with SQL-Server and SQLite


Reply With Quote