The requested page is not available for the requested platform. You are viewing the content for .NET Framework 4.5.2+ platform.

Creating a Persistent Object

The easiest way to define a persistent object is to inherit from the XPObject class. Every persistent object includes the Oid (object identifier) property, which uniquely identifies the object. The XPObject class implements automatic key generation. An auto-generated integer key is mapped to the 'OID' field. Key auto-generation is supported for Int32, Int64 and Guid data types.

Example - Declaring a persistent object


using DevExpress.Xpo;
// ... 
public class Contact : XPObject {
    public string FirstName;
    public string LastName;
}

You can use the DevExpress v19.1 ORM Persistent Object project item template to create a persistent class.

XPObject_Definition

The key properties or fields can also be specified manually. In this instance, you need to inherit your class from the XPCustomObject class. Use the KeyAttribute to mark a property(s) or field(s) as the key. The attribute's KeyAttribute.AutoGenerate property specifies whether the key is generated automatically.

By default, XPO creates a MS Access compatible database in the same directory as the one in which the executable of your application resides. By specifying the default connection, you can easily change this (see How to: Connect to a Data Store). In either case, XPO automatically creates the necessary database structure for you.

The code below creates a Contact table and inserts one record into it.

Example - Creating a Contact record


// Use a line like this to set your own connection string:
// XpoDefault.ConnectionString="...";

Contact contact = new Contact();
contact.FirstName = "John";
contact.LastName =  "Doe";
contact.Save();

Where to Place the Initialization Code for a Persistent Object

Initialization in this section means setting default values for a new XPObject's properties. Later these properties can be modified and saved into a persistent storage (a physical database). When objects are restored from the persistent storage, property values must not be overridden with default values.

To do this, you should override the XPObject's PersistentBase.AfterConstruction method.

The following sample code shows how to override the PersistentBase.AfterConstruction method to set the afterconstructcalled field's value immediately after the TestConstruct object has been initialized.

using DevExpress.Xpo;

class TestConstruct : XPObject {
    [NonPersistent]
    public bool afterconstructcalled = false;
    [NonPersistent]
    public bool constructcalled = false;
    public TestConstruct() {
        constructcalled = true;
    }
    public override void AfterConstruction() {
        base.AfterConstruction();
        afterconstructcalled = true;
    }
}
See Also