Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map string to guid with Dapper

Tags:

I'm using Dapper to hammer out some load testing tools that need to access a PostgreSQL database. This particular version of PostgreSQL does not support GUIDs natively, so GUID values are stored as 32 character strings. The values are converted to strings using someGuid.ToString("N"), conversion back to Guid can be done using new Guid(stringValueFromColumn).

My question is how do I get Dapper to read the strings and convert them back to Guids?

I tried modifying the DbType mapping but that doesn't work.

like image 269
Marnix van Valen Avatar asked May 05 '11 14:05

Marnix van Valen


2 Answers

I'm using MySql but it has the same problem since I store the Guid as a string. To fix the mapping without having to alias the column i used the following:

public class MySqlGuidTypeHandler : SqlMapper.TypeHandler<Guid>
{
    public override void SetValue(IDbDataParameter parameter, Guid guid)
    {
        parameter.Value = guid.ToString();
    }

    public override Guid Parse(object value)
    {
        return new Guid((string)value);
    }
}

And in my Startup.cs:

public void ConfigureServices(IServiceCollection services)
    {
        SqlMapper.AddTypeHandler(new MySqlGuidTypeHandler());
        SqlMapper.RemoveTypeMap(typeof(Guid));
        SqlMapper.RemoveTypeMap(typeof(Guid?));
    }
like image 87
Cpt.Ohlund Avatar answered Sep 20 '22 19:09

Cpt.Ohlund


Perhaps the simplest way to do this (without waiting on dapper) is to have a second property:

public Guid Foo {get;set;}

public string FooString {
    get { return Foo.ToString("N"); }
    set { Foo = new Guid(value); }
}

And in your query, alias the column as FooString.

Of course, then this prompts the question: should dapper support private properties for this type of thing? To which I say: probably.

like image 38
Marc Gravell Avatar answered Sep 19 '22 19:09

Marc Gravell