Skip to main content
All docs
V24.2
.NET 8.0+

Create a Calculated Property

  • 2 minutes to read

This topic explains how to create calculated properties.

The example code below declares a Payment entity 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 previous lesson:

Step-by-Step Instructions

  1. Navigate to the MySolution.Module\Business Objects folder. Create a Payment class. Replace the auto-generated declaration with the following code:

    using DevExpress.ExpressApp.DC;
    using DevExpress.ExpressApp.Model;
    using DevExpress.Persistent.Base;
    using DevExpress.Persistent.BaseImpl.EF;
    
    [DefaultClassOptions]
    public class Payment : BaseObject {
        // Use this attribute to specify the display format pattern for the property value.
        [ModelDefault("DisplayFormat", "{0:c}")]
        public virtual decimal Rate { get; set; }
        public virtual decimal Hours { get; set; }
    
        // Use the `PersistentAlias` attribute to specify the property value calculation expression.
        // Call the `EvaluateAlias` method to access the calculated value.
        [ModelDefault("DisplayFormat", "{0:c}")]
        [PersistentAlias("Rate * Hours")]
        public decimal Amount {
            get { return EvaluateAlias<decimal>(); }
        }
    }
    

    Tip

    You can apply an ImmediatePostDataAttribute to the Rate and Hours properties. If you do so, any change to these properties immediately forces the Amount value to be recalculated.

  2. Register the Payment type in DbContext:

    public class MySolutionEFCoreDbContext : DbContext {
        //...
        public DbSet<Payment> Payments { get; set; }
    }
    
  3. Add a migration and update the database. Review the following help topic for instructions: Implement a Data Model: Basics. Refer to the section titled Use a DBMS: Setup Migrations.

  4. Run the application. Select the Payment item in the navigation control and click New. In the Detail View, change the Rate and Hours properties and note the updated Amount value.

    ASP.NET Core Blazor
    ASP.NET Core Blazor calculable property
    Windows Forms
    Windows Forms calculable property

Next Lesson

Add a Simple Action