Back to Devexpress

Validate Objects

xpo-2039-crud-validate-objects.md

latest2.3 KB
Original Source

Validate Objects

  • Sep 10, 2020
  • 2 minutes to read

eXpress Persistent Objects has no built-in validation logic. You can override the IXPObject.OnSaving or IXPObject.OnDeleting method to implement validation logic. This can be useful, for instance, to perform various checks when implementing ‘defensive programming’. It’s not recommended to mix the process of saving an object with the business logic.

The following example demonstrates how to prevent the Name property from being set to an empty string. If this property is set to an empty string, XPO throws a RequiredPropertyValueMissing exception.

csharp
public class RequiredPropertyValueMissing: Exception {
    public RequiredPropertyValueMissing(XPObject theObject, string propertyName):
        base(String.Format("The {0} property of the {1} object with id {2} must have a value", 
          propertyName, theObject.GetType().Name, theObject.Oid)) {
    }
}

public class Company : Person {
public string Name {
    get { return fName; }
    set { SetPropertyValue(nameof(Name), ref fName, value); }
}
string fName = "";

    protected override void OnSaving() {
        if (Name == "")
          throw new RequiredPropertyValueMissing(this, nameof(Name));
    }
}
vb
Public Class RequiredPropertyValueMissing : Inherits Exception
    Public Sub New(ByVal theObject As XPObject, ByVal propertyName As String)
    MyBase.New(String.Format("The {0} property of the {1} object with id {2} must have a value", _
          propertyName, theObject.GetType().Name, theObject.Oid))
    End Sub
End Class

Public Class Company : Inherits Person
    Public Property Name() As String
        Get
            Return fName
        End Get
        Set(ByVal value as String)
            SetPropertyValue(NameOf(Name), fName, value)
        End Set
    End Property
    Private fName As String = ""

    Protected Overrides Sub OnSaving()
        If (Name = "") Then
            Throw New RequiredPropertyValueMissing(This, NameOf(Name))
        End If
    End Sub
End Class

See Also

IDXDataErrorInfo