githubEdit

Specifications

Structr.Specifications package provides .NET implementation of Specification patternarrow-up-right with set of simple operations with them.

Installation

Specifications package is available on NuGetarrow-up-right.

dotnet add package Structr.Specifications

Usage

Main class of package - Specification<T> - should be inherited by your own classes in order to use its functionality and extensions.

Example of basic usage:

// Some model.
public class Book
{
    public string Title { get; set; }
    public string Author { get; set; }
    public int Year { get; set; }
    public int Price { get; set; }
}

// Specification matching only books written after some year.
public class BookYearIsGreaterThanSpec : Specification<Book>
{
    public int Year { get; }

    public BookYearIsGreaterThanSpec(int year) 
        => Year = year;

    // The only method to be overridden - ToExpression().
    // It should return expression that gives needed condition.
    public override Expression<Func<Book, bool>> ToExpression()
    {
        return x => x.Year > Year;
    }
}

// Specification matching only books which have price less than some value.
public class BookPriceIsLessThanSpec : Specification<Book>
{
    public int Price { get; }

    public BookPriceIsLessThanSpec(int price)
        => Price = price;

    public override Expression<Func<Book, bool>> ToExpression()
    {
        return x => x.Price < Price;
    }
}

Use specifications to filter models collection:

The whole list of Specification<T> extensions is provided below:

Method name
Description

And<T>

Creates specification which will be satisfied only when both specifications will be satisfied by provided instance of type T.

Or<T>

Creates specification which will be satisfied when at least one two specifications will be satisfied by provided instance of type T.

Not<T>

Creates specification which will be satisfied when given specification won't be satisfied by provided instance of type T.

AndNot<T>

Creates specification which will be satisfied when first specification will AND second will not be satisfied by provided instance of T.

OrNot<T>

Creates specification which will be satisfied when first specification will OR second will not be satisfied by provided instance of T.

Additionally two predefined specifications are available:

Name
Description

AnySpecification<T>

Specification to which all objects of T will match.

NoneSpecification<T>

Specification to which none of objects of T will match.

Entity Framework

Structr.Specifications may be helpful with Entity Framework 6arrow-up-right or Entity Framework Corearrow-up-right. Use ToExpression() method with Where() for filtering entities in DbContext:

Last updated