Skip to content

About

Primitives for building reusable LINQ projections and specifications

Topics

Resources

Stars

4 stars

Watchers

2 watching

Forks

Repository files navigation

Build NuGet

Projection Tools

Reusable, composable LINQ specifications (predicates) and projections (mappings) for .NET. Write each rule or mapping once as plain C# and use it everywhere: in EF queries, in in-memory collections, inside other specifications and projections, and in unit tests.

public static readonly Specification<UserEntity> ActiveUser = new(x => x.Active);
public static readonly Specification<UserEntity> AdminUser  = new(x => x.IsAdmin);

// combine with ordinary C# operators
var activeAdmins = await db.Set<UserEntity>().Where(ActiveUser && AdminUser).ToListAsync(); // translated to SQL
var inMemory     = users.Where(ActiveUser && !AdminUser).ToList();                          // runs as a delegate

Highlights

  • One definition, two execution modes. Every specification and projection is both an Expression<Func<...>> (for IQueryable, EF Core, EF6, and other LINQ providers) and a compiled Func<...> (for in-memory objects).
  • Plain C# syntax. Specifications combine with &&, || and !. You don't need builder APIs, base classes or extra interfaces on your entities.
  • Composable. You can use specifications and projections inside other specifications and projections. They are inlined into one flat expression tree, so your LINQ provider sees ordinary LINQ.
  • Parameterized. SpecificationFactory and ProjectionFactory build specifications and projections from runtime arguments.
  • Navigable code. Mappings are ordinary lambdas, so Find Usages, Go to Definition and refactorings work. You don't need runtime configuration, profiles or reflection-based conventions.
  • Lazy and thread-safe. Expressions are rewritten and delegates compiled on first use, and the results are cached. Declaring instances as static readonly fields is safe and cheap.
  • Small footprint. The only dependency is DelegateDecompiler. Targets netstandard2.0, net9.0 and net10.0.

Installation

The package is available on NuGet.

dotnet CLI:

dotnet add package ProjectionTools

Package Manager Console:

Install-Package ProjectionTools

I've also published an article on Medium: Alternative specification pattern implementation in C#.

Sample model

All examples below use this model:

public class UserEntity
{
    public int Id { get; set; }
    public string Name { get; set; }
    public bool Active { get; set; }
    public bool IsAdmin { get; set; }
    public DepartmentEntity MainDepartment { get; set; }
    public List<DepartmentEntity> Departments { get; set; }
}

public class DepartmentEntity
{
    public int Id { get; set; }
    public bool Active { get; set; }
    public string Name { get; set; }
}

public class UserDto
{
    public string Name { get; set; }
    public List<DepartmentDto> Departments { get; set; }
}

public class DepartmentDto
{
    public string Name { get; set; }
}

Specifications

Predicates can get complex. They are often combinations of other predicates that depend on business logic. Existing .NET implementations of the specification pattern tend to share the same problems:

  • Verbose syntax for declaration and usage.
  • Many intrusive extension methods that clutter project code.
  • They only work in one context: either delegates or expressions, but not both.

Specification<TSource> solves all of these problems.

Creating specifications

From an expression (the delegate is compiled from it on first use):

Specification<DepartmentEntity> ActiveDepartment = new(
    x => x.Active
);

From a delegate (the expression is produced by decompiling the delegate with DelegateDecompiler):

Specification<DepartmentEntity> ActiveDepartment = new(
    default,
    x => x.Active
);

From both. Use this when the expression relies on provider-only features, such as EF DbFunctions, and you want a matching in-memory implementation:

Specification<DepartmentEntity> ActiveDepartment = new(
    x => x.Active,
    x => x.Active
);

When you supply both, the library uses each one as-is. Keeping their behavior consistent is your responsibility.

Combining specifications

Use &&, || and !:

Specification<DepartmentEntity> CustomerServiceDepartment = new(
    x => x.Name == "Customer Service"
);

Specification<DepartmentEntity> ActiveCustomerServiceDepartment = ActiveDepartment && CustomerServiceDepartment;

Specification<DepartmentEntity> InactiveOrOtherDepartment = !ActiveDepartment || !CustomerServiceDepartment;

The result is a new specification with a single merged expression, for example x => x.Active && x.Name == "Customer Service". It is not a chain of invocations, so every LINQ provider can translate it.

Nesting specifications

A specification converts implicitly to Func<TSource, bool> and Expression<Func<TSource, bool>>, so you can use it directly inside another specification:

Specification<UserEntity> ActiveUserInCustomerServiceDepartment = new(
    x => x.Active && x.Departments.Any(CustomerServiceDepartment)
);

x.Departments.Any(CustomerServiceDepartment.IsSatisfiedBy) works too. Either way, the nested specification is inlined: x => x.Active && x.Departments.Any(d => d.Name == "Customer Service").

Applying a specification to a related object

ApplyTo reuses a specification for a different root type:

// Specification<DepartmentEntity> -> Specification<UserEntity>
Specification<UserEntity> UserWithActiveMainDepartment = ActiveDepartment.ApplyTo<UserEntity>(x => x.MainDepartment);
// x => x.MainDepartment.Active

Parameterized specifications

SpecificationFactory<TSource, TParam> (and SpecificationFactory<TSource, TParam1, TParam2>) creates specifications from runtime arguments:

public static readonly SpecificationFactory<UserEntity, string> UserInDepartment = new(
    name => x => x.Departments.Any(d => d.Name == name)
);

var spec = ActiveUser && UserInDepartment.For("Customer Service");

The two-parameter factory supports partial application: factory.For(a) returns a one-parameter factory, and factory.For(a, b) returns a specification.

Full example

public static class UserSpec
{
    public static readonly Specification<DepartmentEntity> ActiveDepartment = new(
        x => x.Active
    );

    public static readonly Specification<UserEntity> ActiveUser = new(
        x => x.Active
    );

    public static readonly Specification<UserEntity> AdminUser = new(
        x => x.IsAdmin
    );

    public static readonly Specification<UserEntity> ActiveAdminUser = ActiveUser && AdminUser;

    public static readonly Specification<UserEntity> ActiveUserInActiveDepartment = new(
        x => x.Active && x.Departments.Any(ActiveDepartment)
    );

    public static readonly SpecificationFactory<UserEntity, string> UserInDepartment = new(
        name => x => x.Departments.Any(d => d.Name == name)
    );
}

public class UserController : Controller
{
    private readonly DbContext _context;

    public UserController(DbContext context)
    {
        _context = context;
    }

    public Task<UserEntity> GetUser(int id)
    {
        return _context.Set<UserEntity>()
            .Where(UserSpec.ActiveUserInActiveDepartment)
            .Where(x => x.Id == id)
            .SingleAsync();
    }

    public Task<UserEntity> GetAdminUser(int id)
    {
        return _context.Set<UserEntity>()
            .Where(UserSpec.ActiveAdminUser)
            .Where(x => x.Id == id)
            .SingleAsync();
    }

    public Task<List<UserEntity>> GetActiveUsersInDepartment(string department)
    {
        return _context.Set<UserEntity>()
            .Where(UserSpec.ActiveUser && UserSpec.UserInDepartment.For(department))
            .ToListAsync();
    }
}

Unit-testing the same rules needs no database:

Assert.That(UserSpec.ActiveAdminUser.IsSatisfiedBy(new UserEntity { Active = true, IsAdmin = true }), Is.True);

Using specifications inline in EF queries (SpecificationVisitor)

Specifications passed directly to Where(...), or nested inside other specifications, are already rewritten. But if you reference a specification inside an ad-hoc query lambda, EF sees an opaque delegate and can't translate it:

_context.Set<UserEntity>()
    .Where(u => u.Departments.Any(UserSpec.ActiveDepartment)); // ad-hoc lambda, not a Specification

SpecificationVisitor rewrites such query trees into plain expressions. With EF Core 7+, you can plug it in globally with a query expression interceptor:

public sealed class SpecificationInterceptor : IQueryExpressionInterceptor
{
    private readonly SpecificationVisitor _visitor = new();

    public Expression QueryCompilationStarting(Expression queryExpression, QueryExpressionEventData eventData)
        => _visitor.Visit(queryExpression);
}

// registration
options.AddInterceptors(new SpecificationInterceptor());

Projections

My initial goal was to replace AutoMapper and similar packages. Mapper libraries tend to share these drawbacks:

  • Mappings are resolved at runtime (sometimes with source generators), so the IDE can't show where a property is mapped.
  • The API is complex, yet limited in many cases.
  • Maintenance costs are high, and breaking API changes are frequent.
  • They don't properly separate the instance API (mapping objects) from the expression API (mapping through LINQ projections), which leads to runtime bugs.
  • You can't be sure a mapping works until you manually test each field in each scenario (instance and LINQ).
  • Testing is awkward. Sometimes you have to build your own tooling just to test mappings.
  • Compatibility with LINQ providers can break between releases.

In most applications, mapping splits into two independent scenarios:

  1. Fetching DTOs from the database with automatic projections.
  2. Mapping DTOs to entities and then saving the modified entities.

Direct mapping from DTO to entity is rarely viable in practice, because of validation, access rights and business logic, so you end up writing custom code for each save operation anyway. If we only need to support the first scenario, there is no need for complex mapper configuration.

Projection<TSource, TResult> defines a reusable mapping that works both in queries and in memory.

Creating projections

From a mapping expression (the delegate is compiled from it on first use):

Projection<DepartmentEntity, DepartmentDto> DepartmentDtoProjection = new(
    x => new DepartmentDto
    {
        Name = x.Name
    }
);

From a delegate (the expression is produced by decompiling the delegate with DelegateDecompiler):

Projection<DepartmentEntity, DepartmentDto> DepartmentDtoProjection = new(
    default,
    x => new DepartmentDto
    {
        Name = x.Name
    }
);

From both. Use this when the expression relies on provider-only features such as DbFunctions. The delegate should match the database's behavior:

Projection<DepartmentEntity, DepartmentDto> DepartmentDtoProjection = new(
    x => new DepartmentDto
    {
        Name = x.Name
    },
    x => new DepartmentDto
    {
        Name = x.Name
    }
);

All three options produce the same expression and delegate. They differ only in performance. Compiling an expression and decompiling a delegate each happen once, lazily, and the result is cached.

Composing projections

You can use projections inside other projections, for single objects (Project(...)) and for collections (Select(...Project)). They are inlined, so the database gets one flat SELECT:

Projection<UserEntity, UserDto> UserDtoProjection = new(
    x => new UserDto
    {
        Name = x.Name,
        Departments = x.Departments
            .Where(ActiveDepartment)                 // specifications work here too
            .Select(DepartmentDtoProjection.Project)
            .ToList()
    }
);

ApplyTo and To chain projections and adapt them to related types:

// Projection<DepartmentEntity, DepartmentDto> -> Projection<UserEntity, DepartmentDto>
var mainDepartmentDto = DepartmentDtoProjection.ApplyTo<UserEntity>(x => x.MainDepartment);

// Projection<UserEntity, UserDto> -> Projection<UserEntity, string>
var userName = UserDtoProjection.To(dto => dto.Name);

Parameterized projections

ProjectionFactory<TSource, TResult, TParam> (and the two-parameter variant) creates projections from runtime arguments:

public static readonly ProjectionFactory<UserEntity, UserDto, bool> UserDtoFactory = new(
    includeInactive => x => new UserDto
    {
        Name = x.Name,
        Departments = x.Departments
            .Where(d => includeInactive || d.Active)
            .Select(DepartmentDtoProjection.Project)
            .ToList()
    }
);

var projection = UserDtoFactory.For(true);

Full example

The controller returns only active users, and each user includes only their active departments:

public static class UserProjections
{
    public static readonly Projection<DepartmentEntity, DepartmentDto> DepartmentDtoProjection = new(
        x => new DepartmentDto
        {
            Name = x.Name
        }
    );

    public static readonly Projection<UserEntity, UserDto> UserDtoProjection = new(
        x => new UserDto
        {
            Name = x.Name,
            Departments = x.Departments
                .Where(UserSpec.ActiveDepartment)
                .Select(DepartmentDtoProjection.Project)
                .ToList()
        }
    );
}

public class UserController : Controller
{
    private readonly DbContext _context;

    public UserController(DbContext context)
    {
        _context = context;
    }

    // option 1: projection executed by the database
    public Task<UserDto> GetUserFromDb(int id)
    {
        return _context.Set<UserEntity>()
            .Where(UserSpec.ActiveUser)
            .Where(x => x.Id == id)
            .Select(UserProjections.UserDtoProjection.ProjectExpression)
            .SingleAsync();
    }

    // option 2: projection executed in memory
    public async Task<UserDto> GetUserInMemory(int id)
    {
        var user = await _context.Set<UserEntity>()
            .Include(x => x.Departments)
            .Where(UserSpec.ActiveUser)
            .Where(x => x.Id == id)
            .SingleAsync();

        return UserProjections.UserDtoProjection.Project(user);
    }
}

Why .ProjectExpression in Select? A Projection converts implicitly to Expression<Func<...>> and Func<...>, but C# can't infer the generic arguments of Select<TSource, TResult> through a user-defined conversion. Where doesn't have this problem because its only generic argument comes from the source sequence.

Testing projections

The expression and the delegate come from one definition, so you can test both execution modes without a database:

var entity = new UserEntity { Name = "John", Departments = [new() { Name = "IT", Active = true }] };

var inMemory = UserProjections.UserDtoProjection.Project(entity);
var viaExpression = UserProjections.UserDtoProjection.ProjectExpression.Compile()(entity);

License

MIT

About

Primitives for building reusable LINQ projections and specifications

Topics

Resources

Stars

4 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages