Skip to main content

Save Persistent Objects

  • 2 minutes to read

To save a persistent object use any of the following API:

  • the object’s XPBaseObject.Save method - saves the current object.
  • the session’s Session.Save method - saves a single or multiple persistent objects.
  • UnitOfWork.CommitChanges method - saves all the changes made to the persistent objects, when using the Unit Of Work.
using(UnitOfWork uow = new UnitOfWork()) {
    Person p1 = new Person(uow, "Mike");
    // p1.Save(); when working with a Session

    p2 = new Person(uow, "John");
    // p2.Save(); when working with a Session

    p3 = new Person(uow);
    p.Name = "Bob";
    p.Location = "US";
    // p3.Save(); when working with a Session

    // Save all the changes made
    uow.CommitChanges();
}

When you save a persistent object, XPO automatically saves all referenced objects that are aggregated (see AggregatedAttribute) and any referenced newly created non-aggregated objects that don’t yet exist in a data store.

Note

When a UnitOfWork is used, there is no need to save each persistent object individually. Call the unit of work’s UnitOfWork.CommitChanges method to save all the changes made to the persistent objects.

How It Works

XPO allows persistent objects to be saved to one database and each persistent object to one table. Although you can have several XPO sessions connected to different databases and even make a list of objects from different sessions, these objects should not reference each other (the XPO session will throw an error on saving an object which was read by another session).

When XPO saves an object it starts an implicit transaction, if there isn’t one already running. This is necessary to save complex objects. You don’t need to worry about saving these types of data as XPO manages them.

If you manually start a transaction, you can discard all the changes made since the transactions start by calling the Session.RollbackTransaction method. For more information on using transactions, see Processing Transactions.