Map string to guid with Dapper

c# dapper orm sql

Question

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.

Accepted Answer

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.


Popular Answer

This is an old question but I feel it needs updating as Dapper now supports private properties, which Marc referenced to in his answer.

private String UserIDString { get; set; }
public Guid UserID
{
    get
    {
        return new Guid(UserIDString);
    }
    private set
    {
        UserID = value;
    }
}

Then in SQL give your ID column an alias to map it to the private property and not the actual property:

SELECT UserID AS UserIDString FROM....



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