Specification icon indicating copy to clipboard operation
Specification copied to clipboard

Add FAQ entry on combining specs

Open ardalis opened this issue 1 year ago • 1 comments

ardalis avatar Dec 11 '23 19:12 ardalis

The approach with predicates won't work. EF will throw an exception during the evaluation. Instead, we can write extensions to the builder.

public static class CustomerSpecExtensions
{
    public static ISpecificationBuilder<Customer> IsAdult(this ISpecificationBuilder<Customer> builder)
        => builder.Where(x => x.Age >= 18);

    public static ISpecificationBuilder<Customer> IsAtLeastYearsOld(this ISpecificationBuilder<Customer> builder, int years)
        => builder.Where(x => x.Age >= years);
}

public class AdultCustomersByNameSpec : Specification<Customer>
{
    public AdultCustomersByNameSpec(string nameSubstring)
    {
        Query.IsAdult()
            .Where(x => x.Name.Contains(nameSubstring));
    }
}

We have more examples in the sample apps. https://github.com/ardalis/Specification/blob/main/sample/Ardalis.Sample.Domain/Specs/CustomerSpecExtensions.cs

fiseni avatar Dec 11 '23 20:12 fiseni