-
-
Notifications
You must be signed in to change notification settings - Fork 3.7k
Labels
Milestone
Description
I have an enum that is serialized to the DB using a single letter code.
I tried adding a custom type handler for the enum to handle the conversion but dapper seems to ignore the custom type handler.
Given the example code I expected to see the values;
ID = 10, Type = B
ID = 1, Type = Foo
What I actually got was:
ID = 1, Type = 2
DataException, Error parsing column 1 (Type=F - String)
void Main()
{
SqlMapper.AddTypeHandler(new ItemTypeHandler());
using (var connection = new SqlConnection("Server=(local); Database=tempdb; Integrated Security=SSPI")) {
connection.Open();
connection.Query ("SELECT @ID AS ID, @Type AS Type", new Item {ID = 10, Type = ItemType.Bar}).Dump();
connection.Query<Item> ("SELECT 1 AS ID, 'F' AS Type").Dump();
}
}
class ItemTypeHandler : SqlMapper.TypeHandler<ItemType>
{
public override ItemType Parse(object value)
{
var c = ((string) value) [0];
switch (c) {
case 'F': return ItemType.Foo;
case 'B': return ItemType.Bar;
default: throw new ArgumentOutOfRangeException();
}
}
public override void SetValue(IDbDataParameter p, ItemType value)
{
p.DbType = DbType.AnsiStringFixedLength;
p.Size = 1;
if (value == ItemType.Foo)
p.Value = "F";
else if (value == ItemType.Bar)
p.Value = "B";
else
throw new ArgumentOutOfRangeException();
}
}
class Item
{
public long ID { get; set; }
public ItemType Type { get; set; }
}
enum ItemType
{
Foo = 1,
Bar = 2,
}jcberleur, wmate, marcrocny, ayoung, dmoka and 39 more