ardalis / Specification

Base class with tests for adding specifications to a DDD model
MIT License
1.83k stars 238 forks source link

Add FAQ entry on combining specs #380

Open ardalis opened 5 months ago

fiseni commented 5 months ago

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