Back to Devexpress

XPBaseObject.Save() Method

xpo-devexpress-dot-xpo-dot-xpbaseobject.md

latest12.3 KB
Original Source

XPBaseObject.Save() Method

Saves the object to the data store.

Namespace : DevExpress.Xpo

Assembly : DevExpress.Xpo.v25.2.dll

NuGet Package : DevExpress.Xpo

Declaration

csharp
public void Save()
vb
Public Sub Save

Remarks

The Save method also saves all the referenced objects that are aggregated (see the AggregatedAttribute topic for information) and any referenced newly created non-aggregated objects that don’t yet exist in the data store.

Note

The Save method saves the object immediately when the current persistent object is loaded using Session. If the UnitOfWork is used, the method marks the persistent object as modified and forces the UnitOfWork to include it into the further commit operation. UnitOfWork automatically collects new objects and tracks modified objects using the OnChanged method.

Example

The following example demonstrates how to work with transactions.

In this example, the transaction begins when a persistent object is saved. The Session.BeginTransaction method marks the starting point of the transaction. If the value of the persistent object’s Amount property is negative, the Session.RollbackTransaction method is called which completes the transaction discarding all the changes made since the transaction was started.

Otherwise, if the Amount property’s value isn’t negative, the Session.CommitTransaction method is called to complete the transaction and save all the data modifications made.

csharp
using System;
using DevExpress.Xpo;
using DevExpress.Xpo.DB;

namespace ConsoleApplication1 {
    class Account : XPObject {
        public const double DefaultAmount = 100;
        private double amount = DefaultAmount;
        public Account(Session session) : base(session) { }
        public double Amount {
            get { return amount; }
            set { SetPropertyValue<double>(nameof(Amount), ref amount, value); }
        }
        protected override void OnSaving() {
            base.OnSaving();
            if (!IsDeleted) {
                if (Amount < 0) {
                    throw new Exception("Negative amount!");
                }
            }
        }
    }

    class Program {
        static void Main(string[] args) {
            string connectionString = MSSqlConnectionProvider.GetConnectionString("(local)", "ConsoleApplication1");
            XpoDefault.DataLayer = XpoDefault.GetDataLayer(connectionString, AutoCreateOption.DatabaseAndSchema);
            TransferAmount(100);
            TransferAmount(200);
            Console.WriteLine("Press <Enter> to exit");
            Console.ReadLine();
        }

        static void TransferAmount(double amount) {
            using (Session session = new Session()) {
                Console.WriteLine("Creating Account1 with amount = " + Account.DefaultAmount);
                Account account1 = new Account(session);
                account1.Save();
                Console.WriteLine("Creating Account2 with amount = " + Account.DefaultAmount);
                Account account2 = new Account(session);
                account2.Save();
                Console.WriteLine("");
                Console.WriteLine("Beginning the transaction...");
                session.BeginTransaction();
                try {
                    Console.WriteLine(String.Format(" Withdrawing {0} from Account1", amount));
                    account1.Amount -= amount;
                    account1.Save();
                    Console.WriteLine(String.Format(" Transferring {0} to Account2", amount));
                    account2.Amount += amount;
                    account2.Save();
                    Console.WriteLine("Committing the transaction...");
                    session.CommitTransaction();
                }
                catch (Exception e) {
                    Console.WriteLine("Exception message: " + e.Message);
                    Console.WriteLine("Rolling back the transaction");
                    session.RollbackTransaction();
                    Console.WriteLine("Reloading the accounts from database...");
                    account1.Reload();
                    account2.Reload();
                }
                Console.WriteLine("Account1 amount: " + account1.Amount);
                Console.WriteLine("Account2 amount: " + account2.Amount);
                Console.WriteLine();
            }
        }
    }
}
vb
Imports System
Imports DevExpress.Xpo
Imports DevExpress.Xpo.DB

Namespace ConsoleApplication1
    Friend Class Account
        Inherits XPObject

        Public Const DefaultAmount As Double = 100
        Private _amount As Double = DefaultAmount
        Public Sub New(ByVal session As Session)
            MyBase.New(session)
        End Sub
        Public Property Amount() As Double
            Get
                Return _amount
            End Get
            Set(ByVal value As Double)
                SetPropertyValue(Of Double)(NameOf(Amount), _amount, value)
            End Set
        End Property
        Protected Overrides Sub OnSaving()
            MyBase.OnSaving()
            If Not IsDeleted Then
                If Amount < 0 Then
                    Throw New Exception("Negative amount!")
                End If
            End If
        End Sub
    End Class

    Friend Class Program
        Shared Sub Main(ByVal args() As String)
            Dim connectionString As String = MSSqlConnectionProvider.GetConnectionString("(local)", "ConsoleApplication1")
            XpoDefault.DataLayer = XpoDefault.GetDataLayer(connectionString, AutoCreateOption.DatabaseAndSchema)
            TransferAmount(100)
            TransferAmount(200)
            Console.WriteLine("Press <Enter> to exit")
            Console.ReadLine()
        End Sub

        Private Shared Sub TransferAmount(ByVal amount As Double)
            Using session As New Session()
                Console.WriteLine("Creating Account1 with amount = " & Account.DefaultAmount)
                Dim account1 As New Account(session)
                account1.Save()
                Console.WriteLine("Creating Account2 with amount = " & Account.DefaultAmount)
                Dim account2 As New Account(session)
                account2.Save()
                Console.WriteLine("")
                Console.WriteLine("Beginning the transaction...")
                session.BeginTransaction()
                Try
                    Console.WriteLine(String.Format(" Withdrawing {0} from Account1", amount))
                    account1.Amount -= amount
                    account1.Save()
                    Console.WriteLine(String.Format(" Transferring {0} to Account2", amount))
                    account2.Amount += amount
                    account2.Save()
                    Console.WriteLine("Committing the transaction...")
                    session.CommitTransaction()
                Catch e As Exception
                    Console.WriteLine("Exception message: " & e.Message)
                    Console.WriteLine("Rolling back the transaction")
                    session.RollbackTransaction()
                    Console.WriteLine("Reloading the accounts from database...")
                    account1.Reload()
                    account2.Reload()
                End Try
                Console.WriteLine("Account1 amount: " & account1.Amount)
                Console.WriteLine("Account2 amount: " & account2.Amount)
                Console.WriteLine()
            End Using
        End Sub
    End Class
End Namespace

The following code snippets (auto-collected from DevExpress Examples) contain references to the Save() method.

Note

The algorithm used to collect these code examples remains a work in progress. Accordingly, the links and snippets below may produce inaccurate results. If you encounter an issue with code examples below, please use the feedback form on this page to report the issue.

XPO_how-to-create-and-use-the-joinoperand-using-linq-to-xpo-and-criteria-operators-e1883/CS/E1883/Program.cs#L62

csharp
if (uow.FindObject<Person>(null) != null) return;
new Person(uow) { Name = "Maria Anders", Age = 29 }.Save();
new Person(uow) { Name = "Ana Trujillo", Age = 43 }.Save();

xaf-how-to-display-a-list-of-non-persistent-objects/CS/UnboundListView.Module/Updater.cs#L17

csharp
bookOne.Title = "A Visitor For Bear";
bookOne.Save();

xaf-win-enable-inplace-editing-in-tree-list-view/CS/WinSolution.Module/Updater.cs#L28

csharp
pr.ProjectAreas.Add(pa);
p1.Save();
p2.Save();

winforms-treelist-expression-editor-xpview/CS/E1887/Program.cs#L31

csharp
parent.Quantity = 12;
parent.Save();
Order child = new Order(uow);

xaf-custom-list-editor-blazor/CS/MySolution.Module/DatabaseUpdate/Updater.cs#L37

csharp
image1.Image = GetImageFromResource("MySolution.Module.ListEditorImages.green.png");
    image1.Save();
}

xaf-how-to-display-a-list-of-non-persistent-objects/VB/UnboundListView.Module/Updater.vb#L21

vb
bookOne.Title = "A Visitor For Bear"
bookOne.Save()

xaf-win-enable-inplace-editing-in-tree-list-view/VB/WinSolution.Module/Updater.vb#L32

vb
pr.ProjectAreas.Add(pa)
p1.Save()
p2.Save()

winforms-treelist-expression-editor-xpview/VB/E1887/Program.vb#L32

vb
parent.Quantity = 12
parent.Save()
Dim child As Order = New Order(uow)

XPO_how-to-track-changes-made-to-persistent-objects-and-write-them-into-a-separate-table-e2419/VB/Q149895/Northwind.vb#L27

vb
modInfo.NewValue = change.Value
    modInfo.Save()
Next change

winforms-grid-implement-crud-operations-xpinstantfeedbacksource/VB/DXServermode2/Form1.vb#L128

vb
Try
    customerToEdit.Save()
    session1.CommitTransaction()

See Also

Delete()

XPBaseObject Class

XPBaseObject Members

DevExpress.Xpo Namespace