Skip to main content
.NET Framework 4.6.2+

UnitOfWork Class

Maintains a list of persistent objects that are affected by a transaction. Keeps track of every change to every persistent object during a transaction that can affect a data store.

Namespace: DevExpress.Xpo

Assembly: DevExpress.Xpo.v24.2.dll

Declaration

public class UnitOfWork :
    Session

Remarks

Unit of Work maintains a list of persistent objects that are affected by a transaction. It keeps track of every change to every persistent object during a transaction that can affect a data store. With a single call to the UnitOfWork.CommitChanges method, all the changes made to the persistent objects are automatically saved to a data store. When working with common sessions, you need to save each persistent object individually.

Unit of Work inherit the base functionality from the Session class and provide the UnitOfWork.CommitChanges method that is used to save all changed persistent objects to a data store. The only requirement for this is that the property setters call the XPBaseObject.OnChanged method. To simplify things, you can call the SetPropertyValue method to meet the requirement, as shown in the Create a Persistent Object article.

Using Units of Work in XPO

Create a New Data Item and Save it in a Data Store

using(UnitOfWork uow = new UnitOfWork()) {
    // Create a new object within a Unit of Work
    Person p = new Person(uow);
    p.Name = "Bob";
    p.Location = "U.S.";

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

Get Data Items from a Data Store

using(UnitOfWork uow = new UnitOfWork()) {
    // Get a single item by its key
    var p = uow.GetObjectByKey<Person>(key);

    // Get all the items
    var allPersons = uow.Query<Person>().ToList();

    // Get all the items whose Person.Position property value is "Employee"
    var employees =  uow.Query<Person>().Where(x => x.Position == "Employee").ToList();

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

Update Data Items in a Data Store

using(UnitOfWork uow = new UnitOfWork()) {
    // Get a single item by its key
    var p = uow.GetObjectByKey<Person>(key);

    // Modify a requested data item
    p.Name = "Alice";

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

Delete Data Items from a Data Store

using(UnitOfWork uow = new UnitOfWork()) {

    // Get a single item by its key
    var p = uow.GetObjectByKey<Person>(key);
    // Delete a single data item
    p.Delete();


    // Get all the items whose Person.Position property value is "Employee"
    var employees =  uow.Query<Person>().Where(x => x.Position == "Employee").ToList();
    // Delete a collection of data items
    uow.Delete(employees);

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

Implements

See Also