Skip to content

Value Converters

Aaron Sherber edited this page Mar 27, 2019 · 4 revisions

While mappers allow you to control type conversions on a global, per-database, or per-type basis, value converters let you apply a custom conversion to specific properties of a class.

For example, consider the example of a POCO with an enum property which needs to be stored in the database as a char. With the following basic code, PetaPoco will default to converting the enum to and from its underlying int value, which will cause errors.

public enum Status
{
    New = 'N',
    Complete = 'C',
    Error = 'E'
}

public class MyClass
{
    public int ID { get; set; }
    public Status Status { get; set; }
}

Instead, you can define your own ValueConverter descendant to control the conversion, and apply it to the Status property.

public class StatusEnumConverterAttribute: ValueConverterAttribute
{
    public override object ConvertFromDb(object value)
    {
    	// Error checking is left as an exercise for the reader
    	return (Status)((string)value)[0];
    }
    
    public override object ConvertToDb(object value)
    {
    	return (char)value;
    }
}

public class MyClass
{
    public int ID { get; set; }
    [StatusEnumConverter]
    public Status Status { get; set; }
}