I have data stored in the DB as BINARY(16)
and I would like to select the data using dapper and have it mapped to a model property that is a Guid
. What is a good way of doing this?
Dapper 1.50.4
If all your guid in our database are stored as BINARY(16) I would go on and create a Custom Type Handler to automatically convert the binary format to GUID. Something like:
class BinaryGuid {
public Guid Guid;
public BinaryGuid(byte[] binaryGuid) {
<your-code-here>
}
}
public class BinaryGuidHandler: SqlMapper.TypeHandler<BinaryGuid>
{
public override Roles Parse(object value)
{
<your-code-here>
}
public override void SetValue(IDbDataParameter parameter, BinaryGuid value)
{
<your-code-here>
}
}
then you register it for Dapper to use
SqlMapper.AddTypeHandler(new BinaryGuidHandler());
and you should be good to go:
var r = conn.Query<BinaryGuid>("SELECT MyBinaryGuid FROM MyTable")
I've written an article (and samples) on how to manage custom types in Dapper here:
https://medium.com/dapper-net/custom-type-handling-4b447b97c620