I have a class called AdviceId which supports implicit conversion to/from strings. I have also overridden the ToString() method on the class to ensure that the correct string output is returned whenever this method is called.
My application persists data using Dapper. Previously AdviceIds were persisted and retrieved as strings, but I've now tried to use the specific type instead. However, this fails. Is there a special trick to tell Dapper to use implicit conversion between a string and my AdviceId type?
UPDATE I have managed to get Dapper to insert an instance of AdviceId as a string by adding a type map to the SqlMapper
SqlMapper.AddTypeMap(typeof(AdviceId), DbType.String);
and by making AdviceId implement IConvertible. However, I've had no luck converting a string, from the db, back to an instance of AdviceId.
It looks like Marc added in June 2014 and you can call AddTypeHandler
with your own implementation of SqlMapper.TypeHandler<AdviceId>
which I found via this blog but Marc also blogged here.
public class AdviceIdTypeHandler : SqlMapper.TypeHandler<AdviceId>
{
public override void SetValue(IDbDataParameter parameter, AdviceId value)
{
parameter.Value = value.ToString();
}
public override AdviceId Parse(object value)
{
return new AdviceId((string)value);
}
}
SqlMapper.AddTypeHandler(new AdviceIdTypeHandler());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With