Color Properties in XPO
- 2 minutes to read
This topic demonstrates two approaches to store a System.Drawing.Color
property value in the database managed by the eXpressPersistent Objects ORM.
The first approach is to implement a Value Converter.
using System; using System.Drawing; using DevExpress.Xpo.Metadata; // ... public class ColorValueConverter : ValueConverter { public override object ConvertFromStorageType(object obj) { if(obj == null) { return null; } return Color.FromArgb((Int32)obj); } public override object ConvertToStorageType(object obj) { if(obj == null) { return null; } return ((Color)obj).ToArgb(); } public override Type StorageType { get { return typeof(Int32); } } }
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 Color type.
using DevExpress.Xpo; using System.Drawing; //... private Color color; [ValueConverter(typeof(ColorValueConverter))] public Color Color { get { return color; } set { SetPropertyValue(nameof(Color), ref color, value); } }
Another approach is to convert the Color type to Int32 on property implementation using
get
andset
accessors, as shown below.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(nameof(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.