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.
Code:
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);
}
Usage
To use either one, before interacting with data with Dapper call one or both, here its done in a class constructor.
Code:
public DapperOperations()
{
SqlMapper.AddTypeHandler(new SqlDateOnlyTypeHandler());
SqlMapper.AddTypeHandler(new SqlTimeOnlyTypeHandler());
}
Alternate, add the following NuGet package kp.Dapper.Handlers and in the GitHub repository there are samples.
Tested with SQL-Server and SQLite