Pregunta

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?

¿Fue útil?

Solución

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

Otros consejos

If comma-separated strings are common in your database, then implementing IMapper is probably your best option. However, if this only occurs once in your schema, it might be simpler and more maintainable to do something like this:

[PetaPoco.Column("Bars")]
public string BarCsvString { get; set; }

[PetaPoco.Ignore]
public IEnumerable<string> Bars { get { return BarCsvString.Split(","); } }

(Note - I'm pretty sure PetaPoco.Ignore is assumed on read-only properties.)

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top