Skip to main content
.NET 8.0+

How to: Use Read-Only Persistent Properties

  • 3 minutes to read

In this document, you will learn how to define a read-only persistent property of a persistent object. The value of this property is set only once when the object is created. Thereafter, it is never changed. Generally, XPO stores only writable properties, but in certain scenarios, you may need to store the values of read-only properties in the database.

First, a property without a “setter” method in a persistent class must be created. By default, this property is non-persistent and its value can be stored in a private field. Private fields are also non-persistent members of an XPObject. To mark it as persistent, add a PersistentAttribute to the field with the name of the read-only property. This name will be used as the column’s name in the database table that corresponds to the persistent object. To avoid data store overhead, associate the public property with the persistent field using the PersistentAliasAttribute, as shown in the following code snippet.

public class Client : XPObject {
    [Persistent("ClientID")]
    private string clientID;

    [PersistentAlias(nameof(clientID))]
    public string ClientID {
        get { return clientID; }
    }

    public Client(string clientID) {
        // The clientID is passed as a parameter in the persistent object's constructor.
        // Its value is specified only for a new object and cannot be changed afterwards.
        this.clientID = clientID;
    }

    public Client(Session session) : base(session) {}
}

Note

The property is marked with the PersistentAliasAttribute, to be able to use it in filtering, searching, and inclusion in XPBaseCollection.DisplayableProperties.

Another useful example of using read-only persistent properties is saving the object’s creation date.

public class Company: XPObject {
    // ...
    [Persistent("CreatedOn")]
    DateTime createdOn = DateTime.Today;
    // Marked as persistent to use the CreatedOn property in selection criteria.
    [PersistentAlias(nameof(createdOn))]
    public DateTime CreatedOn { get { return createdOn; }}
}
See Also