Skip to content

Instantly share code, notes, and snippets.

@krake747
Last active January 28, 2024 15:14
Show Gist options
  • Save krake747/bfe6a4c13843cc997bf572a7f780653d to your computer and use it in GitHub Desktop.
Save krake747/bfe6a4c13843cc997bf572a7f780653d to your computer and use it in GitHub Desktop.
PostgreSQL Dapper DateOnly and TimeOnly Type Handlers
using System.Data;
using Dapper;
namespace Krake747.Infrastructure.TypeHandlers.Npgsql;
internal sealed class DateOnlyTypeHandler : SqlMapper.TypeHandler<DateOnly>
{
public override DateOnly Parse(object value) => DateOnly.FromDateTime((DateTime)value);
public override void SetValue(IDbDataParameter parameter, DateOnly value)
{
parameter.DbType = DbType.Date;
parameter.Value = value;
}
}
internal sealed class TimeOnlyTypeHandler : SqlMapper.TypeHandler<TimeOnly>
{
public override TimeOnly Parse(object value)
{
if (value is DateTime time)
{
return TimeOnly.FromDateTime(time);
}
return value is TimeSpan timeSpan ? TimeOnly.FromTimeSpan(timeSpan) : default;
}
public override void SetValue(IDbDataParameter parameter, TimeOnly value)
{
parameter.DbType = DbType.Time;
parameter.Value = value;
}
}
public static class InfrastructureServiceCollectionExtensions
{
public static IServiceCollection AddTypeHandlers(this IServiceCollection services)
{
SqlMapper.AddTypeHandler(new DateOnlyTypeHandler());
SqlMapper.AddTypeHandler(new TimeOnlyTypeHandler());
return services;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment