Skip to content

PreparedTrigger_MaintainCount

github-actions[bot] edited this page Dec 6, 2026 · 3 revisions

Use PreparedTrigger_MaintainCount<TSource, TTarget> on the entity whose rows you want to count. Here each product with a BrandID contributes one to that brand’s ProductsCount. A product with a null BrandID contributes zero. Moving a product to another brand decrements the old brand and increments the new one. Deleting the product removes its contribution.

using Blueprint.Entities.Triggers.PreparedTriggers;

[Entity("Brands")]
public abstract class Brand : BlueprintEntityDB
{
    [DefaultValue(0), DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    public abstract int ProductsCount { get; }
}

[Entity("Products", UseSqlOutputClause = false)]
public abstract class Product : BlueprintEntityDB
{
    /// <summary>Defines the trigger that maintains each brand's product count.</summary>
    /// <returns>The prepared count trigger.</returns>
    public override List<BlueprintEntityTrigger> getDatabaseTriggers()
    {
        return [new PreparedTrigger_MaintainCount<Product, Brand>("TR_Products_BrandProductsCount", nameof(BrandID), nameof(Brand.ProductsCount))];
    }

    public abstract long? BrandID { get; set; }

    [ForeignKey(nameof(BrandID))]
    public abstract Brand? Brand { get; set; }

    public abstract bool IsActive { get; set; }
}

The foreign key must be a mapped long or long? referencing the target ID. Declare the stored int counter with the attributes shown to configure its zero default and database-generated value.

Register the source contract on an initialized SQL Server database. The mapped reference brings in Brand.

database.RegisterEntities(typeof(Product));

The first installation creates the trigger and counts existing rows in one transaction. Repeating the call with the same trigger name on the same table leaves the existing trigger and counts in place. To take over the same count from an earlier application version, use the existing SQL trigger name. Apply a schema migration when changing the installed definition or renaming the trigger.

By default, the trigger counts every assigned product. The optional include predicate can restrict the count to active products. It supports comparisons of mapped, non-nullable Boolean, enum and integer properties with literals, combined with &&, || and !.

Bulk writes must fire triggers to update the count.

Entity triggers and common imports

Clone this wiki locally