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:
- Inherit from the Business Class Library Class (XPO/EF core)
- Place an Action in a Different Location
Step-by-Step Instructions
- Create a
Payment
business object in the MySolution.Module project. 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 noset
accessor. Its value calculation takes place in theget
accessor.For EF Core-based applications, register the
Payment
type in theDbContext
:public class MySolutionEFCoreDbContext : DbContext { //... public DbSet<Payment> Payments { get; set; } }
For EF Core-based applications, add a migration and update the database. See the following section for details: Use a DBMS: Setup Migrations.
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.