Dapper icon indicating copy to clipboard operation
Dapper copied to clipboard

Problems with SqlMapper.TypeHandler<List<string>>

Open eliaquimmauricio opened this issue 2 years ago • 0 comments

I'm trying to resolve a problem with a class that contains a List<string> property.

In this case, when I use a QueryFirstOrDefault, Dapper does not fill the property correctly, throwing an error.

I'd like to receive an object of the class, with the property filled with a list of one item.

For that, I've created this:

public class ListStringTypeHandler : SqlMapper.TypeHandler<List<string>>
{
        public override void SetValue(IDbDataParameter parameter, List<string> value)
        {
            parameter.Value = string.Join(",", value);
        }

        public override List<string> Parse(object value)
        {
            if (value == null || value is DBNull)
                return new List<string>();

            if (value is string stringValue)
                return new List<string> { stringValue };

            return new List<string>((IEnumerable<string>)value);
        }
}

But, after that, every single query that contains a IN clause, don't work more.

Are there any way to override only Parse method ?

Thanks.

eliaquimmauricio avatar Jul 31 '23 20:07 eliaquimmauricio