Search code examples
c#sqlormdapper

Map string to guid with Dapper


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.


Solution

  • 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.