Skip to content

collection relational queries

vijay@envivo edited this page Oct 20, 2026 · 8 revisions

Relational Queries

Aggregates with large contents can lead to poor performance if you attempt to fully load the Aggregate while working working on it.

A typical example is Account and Payments, where the Account may own hundreds (or thousands) of Payment objects.

To improve performance, the UI can load the collection property on-demand using RelationalQuerySpecificationAttribute.

  1. Create a context dependent QuerySpecification

    public class AccountPaymentsQuerySpecification : IQuerySpecification<Payment>👈
    {
        public AccountPaymentsQuerySpecification(DbContext repo)
        {
            _Repo = repo;
        }
    
        ...
    
        public Task<IEnumerable<Payment>> GetResultsAsync(CancellationToken cancellationToken)
        {
            IEnumerable<Payment> matches = [];
            return Task.FromResult(matches);
        }
    
        public Task<IEnumerable<Payment>> GetResultsAsync(Account account, CancellationToken cancellationToken)👈
        {
            var matches = _Repo.Payments.Where(p => p.AccountRef.AggregateId == account.Id); 👈
            return Task.FromResult(matches);
        }
    }
  2. Modify the aggregate root so that it loads the collection on-demand:

    public class Account : IAggregateRoot
    {
        ...
    
        [Relationship(RelationshipType.Owns)]
        [Ui(UiRenderOption.SeparateTabExpanded)]
        [RelationalQuerySpecification(typeof(AccountPaymentsQuerySpecification)]👈
        public ICollection<Payment> Payments { get; set; } = [];
        ...
    }

💡 Developer Tips

RelationalQuerySpecificationAttribute reminds you that the property's contents should be stored separately from the main aggregate, and explicitly loaded when needed.

Clone this wiki locally