Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dapper and implicit conversion of strings to custom types

Tags:

c#

dapper

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.

like image 200
Øyvind Avatar asked May 06 '14 18:05

Øyvind


1 Answers

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());
like image 51
Iain Avatar answered Oct 16 '22 15:10

Iain