Skip to main content
A newer version of this page is available. .
All docs
V22.1
.NET Framework 4.5.2+

Create a Calculated Property

  • 3 minutes to read

This lesson explains how to create calculated properties.

The instructions below explain how to add a Payment class with the following properties:

  • Rate (a persistent property)
  • Hours (a persistent property)
  • Amount (a non-persistent, calculated property: Amount = Rate * Hours)

Note

Before you proceed, take a moment to review the following lessons:

Step-by-Step Instructions

  1. Create a Payment business object in the MySolution.Module project.
  2. Replace the generated class declaration with the following code:

    using DevExpress.Persistent.Base;
    using DevExpress.Persistent.BaseImpl;
    using DevExpress.Xpo;
    // ...
    [DefaultClassOptions]
    public class Payment : BaseObject {
        public Payment(Session session) : base(session) { }
        private double rate;
        public double Rate {
            get {
                return rate;
            }
            set {
                if(SetPropertyValue(nameof(Rate), ref rate, value))
                    OnChanged(nameof(Amount));
            }
        }
        private double hours;
        public double Hours {
            get {
                return hours;
            }
            set {
                if(SetPropertyValue(nameof(Hours), ref hours, value))
                    OnChanged(nameof(Amount));
            }
        }
        /*Use this attribute to specify that the value of this property depends on the values of other fields.
          The expression that you pass as a parameter calculates the property value.*/
        [PersistentAlias("Rate * Hours")]
        public double Amount {
            get { return (double)(EvaluateAlias(nameof(Amount)) ?? 0); }
        }
    }
    

    The Amount property has no set accessor. Its value calculation takes place in the get accessor.

  3. For EF Core-based applications, register the Payment type in the DbContext:

    public class MySolutionEFCoreDbContext : DbContext {
        //...
        public DbSet<Payment> Payments { get; set; }
    }
    
  4. For EF Core-based applications, add a migration and update the database. See the following section for details: Use a DBMS: Setup Migrations.

  5. Run the application. Select the Payment item in the navigation control, and click “New”. In the Payment Detail View, change the Rate and Hours properties to see how this affects the Amount property.

    xaf ASP.NET Core Blazor calculable property

Next Lesson

Format a Property Value

See Also