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
)
Step-by-Step Instructions
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
andHours
properties. If you do so, any change to these properties immediately forces theAmount
value to be recalculated.Register the
Payment
type inDbContext
:public class MySolutionEFCoreDbContext : DbContext { //... public DbSet<Payment> Payments { get; set; } }
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.
Run the application. Select the Payment item in the navigation control and click New. In the Detail View, change the
Rate
andHours
properties and note the updatedAmount
value.- ASP.NET Core Blazor
- Windows Forms