Color Properties in XPO

This topic demonstrates two approaches to store a System.Drawing.Color property value in the database managed by the eXpressPersistent Objects ORM.

  1. The first approach is to implement a Value Converter.

    using System;
    using System.Drawing;
    using DevExpress.Xpo.Metadata;
    // ...
    public class ColorValueConverter : ValueConverter {
        public override Type StorageType {
            get { return typeof(Int32); }
        }
        public override object ConvertToStorageType(object value) {
            if(!(value is Color)) return null;
            Color color = (Color)value;
            return color.IsEmpty ? -1 : color.ToArgb();
        }
        public override object ConvertFromStorageType(object value) {
            if(!(value is Int32)) return null;
            Int32 argbCode = Convert.ToInt32(value);
            return argbCode == -1 ? Color.Empty : Color.FromArgb(argbCode);
        }
    }
    

    After that, decorate properties that need to be converted with the ValueConverterAttribute and the converter will be called on each attempt to store or acquire a value of the System.Drawing.Color type.

    using DevExpress.Xpo;
    using System.Drawing;
    //...
    private Color color;
    [ValueConverter(typeof(ColorValueConverter))]
    public Color Color {
        get { return color; }
        set { SetPropertyValue("Color", ref color, value); }
    }
    
  2. Another approach is to convert the System.Drawing.Color type to System.Int32 on property implementation using get and set accessors, as shown below. Mobile applications do not support this approach.

    using DevExpress.Xpo;
    using System.Drawing;
    //...
    [Persistent("Color")]
    private Int32 color;
    [NonPersistent]
    public Color Color {
        get { return Color.FromArgb(color); }
        set {
            color = value.ToArgb();
            OnChanged("Color");
        }
    }
    
    Note

    If the type's class does not have an appropriate conversion method (Color.ToArgb in this case), implement a Type Converter and use it any time you need a value conversion between the type you need to store and an ORM-friendly type.