Skip to content

Overview

Furkan Güngör edited this page Jul 3, 2022 · 1 revision

Ardalis.Specification is one of the best ways to implement specification pattern. That's why Easy Repository.EF Core supports it by default. It is quite simple to use.

Just follow the steps below.

⬇️

Step 1

Install EasyRepository.EFCore.Ardalis.Specification from Nuget

Step 2 Define a specifcation for entity

/// <summary>
/// Author By Name specification
/// </summary>
public sealed class AuthorByNameSpec : Specification<Author>
{
    /// <inheritdoc />
    public AuthorByNameSpec(string name)
    {
        Query.Where(c => c.Name == name);
    }
}

Step 3

Build and apply specification

public class MyClass
{
    private readonly IUnitOfWork _unitOfWork;
    public MyClass(IUnitOfWork unitOfWork)
    {
        _unitOfWork = unitOfWork;
    }
    public async Task<List<Author>> GetByName(string name)
    {
        var queryable = _unitOfWork.Repository.GetQueryable<Author>();
        var spec = new AuthorByNameSpec(name);
        var data = SpecificationConverter.Convert(queryable, spec);
	return data.ToList(); // or data.FirstOrDefault or data.SingleOrDefault
    }
}
Clone this wiki locally