Dapper and implicit conversion of strings to custom types

c# dapper

Question

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.

Popular Answer

It looks like Marc added in June 2014 and you can call AddTypeMap 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());


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why