Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
DateTime / TimeSpan の時刻のみをバイナリ化するソリューション。Dapper 対応版。
using Dapper;
using System;
using System.Data;
namespace InAsync {
public struct TimeOfDay {
public TimeOfDay(long ticks) {
TimeSpan = new TimeSpan(ticks % TimeSpan.TicksPerDay);
}
public TimeSpan TimeSpan { get; }
public byte[] ToBinary() {
var timeTicks = TimeSpan.Ticks;
var bin = new byte[5];
for (var i = 0; i < bin.Length; i++) {
var shift = i * 8;
bin[i] = (byte)(timeTicks >> shift & 0xff);
}
return bin;
}
public static TimeOfDay FromBinary(byte[] bin) {
if (bin == null) throw new ArgumentNullException(nameof(bin));
if (bin.Length != 5) throw new ArgumentException(nameof(bin));
var ticks = 0L;
for (var i = 0; i < bin.Length; i++) {
var shift = i * 8;
ticks |= (long)bin[i] << shift;
}
return new TimeOfDay(ticks);
}
}
/// <summary>
/// Dapper 用 TypeHandler
/// </summary>
public class TimeOfDayHandler : SqlMapper.TypeHandler<TimeOfDay> {
public static readonly TimeOfDayHandler Default = new TimeOfDayHandler();
public override void SetValue(IDbDataParameter parameter, TimeOfDay value) {
parameter.DbType = DbType.Binary;
parameter.Value = value.ToBinary();
}
public override TimeOfDay Parse(object value) {
if (value == null || value is DBNull) {
return default(TimeOfDay);
}
if (value is byte[] bin) {
return TimeOfDay.FromBinary(bin);
}
throw new FormatException("Invalid conversion to TimeOfDay");
}
/// <summary>
/// <see cref="SqlMapper.TypeHandler{TimeOfDay}"/> を登録します。
/// </summary>
public static void Register() {
SqlMapper.AddTypeHandler(Default);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.