Map string to guid with Dapper

前端 未结 6 504
广开言路
广开言路 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:38

    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
    {
        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?));
        }
    

提交回复
热议问题