Last active
January 28, 2024 15:14
-
-
Save krake747/bfe6a4c13843cc997bf572a7f780653d to your computer and use it in GitHub Desktop.
PostgreSQL Dapper DateOnly and TimeOnly Type Handlers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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