Ardalis.Specification Quick Start Guide
-
Install Nuget-Package(s)
a. Always required: Ardalis.Specification
b. If you want to use it with EF Core also install the package Ardalis.Specification.EntityFrameworkCore
c. Alternatively, if you want to use it with EF6 also install the package Ardalis.Specification.EntityFramework6
-
Create a specification by inheriting from
Specification<T>
.public class CustomerByLastNameSpec : Specification<Customer> { public CustomerByLastNameSpec(string lastName) { Query.Where(c => c.LastName == lastName); } }
-
Apply a specification to a
DbSet
orIQueryable
source.var spec = new CustomerByLastNameSpec("Smith"); var customers = await _dbContext.Customers .WithSpecification(spec) .ToListAsync();
-
Alternatively, apply the specification using repositories. Learn how to create and use repositories in the following sections How to use Specifications with the Repository Pattern and How to use the Built In Abstract Repository
var spec = new CustomerByLastNameSpec("Smith"); var customers = await _customerRepo.ListAsync(spec);