Map string to guid with Dapper

前端 未结 6 530
广开言路
广开言路 2020-12-30 03:48

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

6条回答
  •  时光取名叫无心
    2020-12-30 04:23

    It looks like there is UUID type in PostgreSQL already. But @Cpt.Ohlund's solution is still great for MySQL/MariaDB in 2020.

    But the solution might cause problems itself.

    When VARCHAR(36) is used for System.Guid the following exception is thrown:

    System.InvalidCastException: Invalid cast from 'System.String' to 'System.Guid'.

    @Cpt.Ohlund's solution makes it work.

    But if the column is CHAR(36) then it is mapped to System.Guid automatically! And if @Cpt.Ohlund's solution is applied there will be another exception:

    System.InvalidCastException: Unable to cast object of type 'System.Guid' to type 'System.String'.

    The exception is caused by an instance System.Guid passed to Parse(object value) instead of a string.


    So the simple answer is to use CHAR(36) in MySQL and MariaDB and it will just work.

    But if you need to handle any string type of the column you have to use an improved @Cpt.Ohlund's solution:

    public class MySqlGuidTypeHandler : SqlMapper.TypeHandler
    {
        public override void SetValue(IDbDataParameter parameter, Guid guid)
        {
            parameter.Value = guid.ToString();
        }
    
        public override Guid Parse(object value)
        {
            // Dapper may pass a Guid instead of a string
            if (value is Guid)
                return (Guid)value;
    
            return new Guid((string)value);
        }
    }
    

    And register it using SqlMapper.AddTypeHandler().

提交回复
热议问题