Specification
Specification copied to clipboard
Add FAQ entry on combining specs
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