How to: Add a Computed Field

You can create fields that derive their values from the values of other fields. For example, you can add a field named Subtotal to an Order_Details entity. You can specify that the value of the Subtotal field is derived by multiplying the value of the UnitPrice field by the value of the OrderQuantity field.

Note

You cannot include a computed field as part of a filter condition or sort term in a query. Also, you cannot sort information in a screen by clicking the column heading of a computed field.

link to video For a related video demonstration, see How Do I: Write business rules for validation and calculated fields in a LightSwitch Application?.

To define a computed field

  1. In Solution Explorer, double-click an entity or table.

    The entity or table opens in the Data Designer.

  2. In the Data Designer, on the command bar, click Computed Property.

    A new field appears in the bottom row of the entity or table.

  3. In the Name column, click name of the new field, and then type a name (For example: Subtotal).

  4. In Type column of the new field, select a data type (For example: Money).

  5. In the Properties window, click Edit Method.

    The Code Editor opens and generates a method named FieldName**_Compute**.

  6. Add code to the FieldName _Compute method that sets the value of the result parameter. The following example sets the value of the Subtotal field by multiplying the value of the UntiPrice field by the value of the OrderQuantity field.

    Private Sub Subtotal_Compute(ByRef result As Decimal)
        result = Me.Quantity * Me.UnitPrice
    
    partial void Subtotal_Compute(ref decimal result)
    {
        result = this.Quantity * this.UnitPrice;
    }
    

A computed field is not saved to the data source. A computed field appears only in screens that consume the entity or table. In the data designer, a small icon resembling a calculator appears next to computed fields. This icon indicates that the field is used for display purposes only and does not affect the data source of the entity or table.

In most cases, the value of a computed field is recalculated based on changes to any field that you use to derive the value of the computed field. If the value of the computed field does not update, users can refresh the screen to view the updated value. You can also write custom code that refreshes the screen when certain events occur. For more information, see How to: Handle Data Events.

See Also

Tasks

How to: Define Data Fields

How to: Create a Drop-Down List of Values for a Field

Other Resources

Data: The Information Behind Your Application