Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@mibiio
Created October 31, 2017 08:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mibiio/1b4af21987695312d973d97c0b79701b to your computer and use it in GitHub Desktop.
Save mibiio/1b4af21987695312d973d97c0b79701b to your computer and use it in GitHub Desktop.
dapper nodatime npgsql
public class DapperTest
{
public ZonedDateTime DapperTime { get; set;}
}
private void NpgsqlWithDapper()
{
NpgsqlConnection.GlobalTypeMapper.UseNodatime();
SqlMapper.AddTypeHandler(ZonedDateTimeHandler.Default);
using (var connection = new NpgsqlConnection("connection_string"))
{
connection.Open();
var d = connection.Query<DapperTest>("set time zone 'Europe/Vienna'; select now() as dappertime;").First();
Console.WriteLine(d);
}
}
public class ZonedDateTimeHandler : SqlMapper.TypeHandler<ZonedDateTime>
{
private ZonedDateTimeHandler()
{
}
public static readonly ZonedDateTimeHandler Default = new ZonedDateTimeHandler();
public override void SetValue(IDbDataParameter parameter, ZonedDateTime value)
{
parameter.Value = value.ToInstant();
if (parameter is SqlParameter sqlParameter)
{
sqlParameter.SqlDbType = SqlDbType.DateTime2;
}
}
public override ZonedDateTime Parse(object value)
{
Console.WriteLine(value.GetType()); // typeof Instant not ZonedDatetime
if (value is ZonedDateTime dateTime)
{
Console.WriteLine(value);
}
throw new DataException("Cannot convert " + value.GetType() + " to NodaTime.ZonedDateTime");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment