Skip to main content
All docs
V24.1

Create a Calculated Property

  • 2 minutes to read

This lesson explains how to create calculated properties.

For this purpose, add 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. In the MySolution.Module\Business Objects folder, create a Payment class. Replace the generated class declaration with the following code:

    using DevExpress.ExpressApp.Model;
    using DevExpress.Persistent.Base;
    using DevExpress.Persistent.BaseImpl.EF;
    using System.ComponentModel.DataAnnotations.Schema;
    
    [DefaultClassOptions]
    public class Payment : BaseObject
    {
        //Use this attribute to specify the display format pattern for the property value.
        [ModelDefault("DisplayFormat", "{0:c}")]
        public virtual double Rate { get; set; }
        public virtual double Hours { get; set; }
    
        //Use this attribute to exclude the property from database mapping.
        [NotMapped]
        [ModelDefault("DisplayFormat", "{0:c}")]
        public double Amount
        {
            get { return Rate * Hours; }
        }
    
    }
    

    The Amount property does not require a set accessor. Value calculation takes place in the get accessor.

  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. See the following section for details: Use a DBMS: Setup Migrations.

  4. 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.

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

Next Lesson

Add a Simple Action