Back to Devexpress

Save Persistent Objects

xpo-2105-crud-saving-persistent-objects.md

latest2.8 KB
Original Source

Save Persistent Objects

  • May 12, 2022
  • 2 minutes to read

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

csharp
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();
}
vb
Dim uow As UnitOfWork = New UnitOfWork()
Dim p1 As Person = 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()
uow.Dispose()

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.