Search code examples
c#.netormpetapocomicro-orm

PetaPoco map comma separated string to a List of string


In the database, I've got a column that contains comma seperated values, like so:

Foo.Bars varchar(100): @;1,5

In the code, the DTO contains a List<string>, like so:

public class Foo { public List<string> Bars {get; set;} }

I'd like PetaPoco to do the conversion for me.

I've read about the IMapper interface but I couldn't find an example of how to use it.
How can I achieve the desired result?


Solution

  • Here's the solution I think:

    public class ListMapper : IMapper 
    {
        public void GetTableInfo(Type t, TableInfo ti)
        {
        }
    
        public bool MapPropertyToColumn(PropertyInfo pi, ref string columnName, ref bool resultColumn)
        {
            return true;
        }
    
        public Func<object, object> GetFromDbConverter(PropertyInfo pi, Type sourceType)
        {
            return src => 
                {
                    if (sourceType == typeof (string)
                        && pi.PropertyType == typeof (List<string>)
                        && src != null)
                    {
                        return ((string) src).Split(';').ToList();
                    }
                    return src;
                };
        }
    
        public Func<object, object> GetToDbConverter(Type sourceType)
        {
            return null;
        }
    }
    

    Database.Mapper = new ListMapper(); // Mapper is a static property