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
)
Step-by-Step Instructions
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 aset
accessor. Value calculation takes place in theget
accessor.Register the
Payment
type inDbContext
:public class MySolutionEFCoreDbContext : DbContext { //... public DbSet<Payment> Payments { get; set; } }
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
andHours
properties to see how this affects theAmount
property.- ASP.NET Core Blazor
- Windows Forms