Skip to content

Instantly share code, notes, and snippets.

@chilversc
Last active August 29, 2015 14:04
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 chilversc/994509807c177259e77b to your computer and use it in GitHub Desktop.
Save chilversc/994509807c177259e77b to your computer and use it in GitHub Desktop.
Dapper type handler with nullable, now obsolete. Dapper handles this natively as of issue #136
void Main()
{
// SqlMapper.AddTypeHandler<T>(TypeHandler<T>) does not register the nullable version
// Instead, use the SqlMapper.AddTypeHandler(Type, ITypeHandler) overload
SqlMapper.AddTypeHandler(typeof(LocalDate), LocalDateHandler.Default);
// Without this line a NullReferenceException is thrown
SqlMapper.AddTypeHandler(typeof(LocalDate?), LocalDateHandler.Default);
using (var db = new SqlConnection (@"Data Source=.;Initial Catalog=tempdb;Integrated Security=True")) {
db.Open ();
var param = new LocalDateResult {
NotNullable = new LocalDate { Year = 2014, Month = 7, Day = 25 },
NullableNotNull = new LocalDate { Year = 2014, Month = 7, Day = 26 },
NullableIsNull = null,
};
var result = db.Query<LocalDateResult>("SELECT @NotNullable AS NotNullable, @NullableNotNull AS NullableNotNull, @NullableIsNull AS NullableIsNull", param).Single();
result.Dump();
}
}
public class LocalDateHandler : Dapper.SqlMapper.TypeHandler<LocalDate>
{
private LocalDateHandler () { }
// Make the field type ITypeHandler to ensure it cannot be used with SqlMapper.AddTypeHandler<T>(TypeHandler<T>)
// by mistake.
public static readonly SqlMapper.ITypeHandler Default = new LocalDateHandler();
public override LocalDate Parse(object value)
{
var date = (DateTime)value;
return new LocalDate { Year = date.Year, Month = date.Month, Day = date.Day };
}
public override void SetValue(IDbDataParameter parameter, LocalDate value)
{
parameter.DbType = DbType.DateTime;
parameter.Value = new DateTime(value.Year, value.Month, value.Day);
}
}
public struct LocalDate
{
public int Year { get; set; }
public int Month { get; set; }
public int Day { get; set; }
}
public class LocalDateResult
{
public LocalDate NotNullable { get; set; }
public LocalDate? NullableNotNull { get; set; }
public LocalDate? NullableIsNull { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment