Created
October 31, 2017 08:18
-
-
Save mibiio/1b4af21987695312d973d97c0b79701b to your computer and use it in GitHub Desktop.
dapper nodatime npgsql
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
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