Dapper TypeHandler.SetValue() not being called

前端 未结 2 1602
时光取名叫无心
时光取名叫无心 2020-12-16 02:08

I am testing Dapper to load / persist objects to an Oracle database, and to manage Oracle\'s Guid storage I need a SqlMapper.TypeHandler. When loadi

2条回答
  •  既然无缘
    2020-12-16 02:33

    In case anyone else stumbles upon this post with a similar problem, I found a solution to handling Guids without the need for wrappers.

    The problem in Dapper is the order in which Dapper searches for matching DbType and TypeHandler implementations. Dapper prefers "native" DbType for a Guid (in SqlMapper#LookupDbType). In order to make Dapper use your own implementation, you have to remove the default mapping in addition to adding your own TypeHandler:

    SqlMapper.AddTypeHandler(new GuidTypeHandler());
    SqlMapper.RemoveTypeMap(typeof(Guid));
    SqlMapper.RemoveTypeMap(typeof(Guid?));
    

    I currently use a string-based implementation when working with SQLite:

    public class GuidAsStringHandler : SqlMapper.TypeHandler
    {
        public override Guid Parse(object value)
        {
            return new Guid((string) value);
        }
    
        public override void SetValue(IDbDataParameter parameter, Guid value)
        {
            parameter.Value = value.ToString();
        }
    }
    

提交回复
热议问题