Code Monkey home page Code Monkey logo

linqspecs's Introduction

LinqSpecs is a framework that will help you to create specifications for LINQ queries that can be executed by a remote server. You can read more about the specification pattern in Wikipedia.

Almost all users of LINQ create specifications in their daily work, but most of them write those specifications scattered all over the code. The idea behind this project is to help the user to write, test and expose specifications as first-class objects. You will learn how to use LinqSpecs in this brief document.

NuGet Nuget

Defining simple specifications

In order to define our first specification named "CustomerFromCountrySpec" we need to inherit from Specification<T>:

public abstract class Specification<T>
{
    public abstract Expression<Func<T, bool>> ToExpression();
}

So this is our implementation:

using LinqSpecs;

public enum Country { Argentina, France, Italia, ... }

public class CustomerFromCountrySpec : Specification<Customer>
{
    public Country Country { get; set; }

    public CustomerFromCountrySpec(Country country)
    {
        Country = country;
    }

    public override Expression<Func<Customer, bool>> ToExpression()
    { 
        return c => c.Country == Country;
    }
}

Simple as is, to use this class, your repository or DAO should implement these kind of methods:

public IEnumerable<T> Find(Specification<T> specification)
{
    return [a queryable source].Where(specification).ToList();
}

public int Count(Specification<T> specification)
{
    return [a queryable source].Count(specification);
}

The usage is very simple:

var spec = new CustomerFromCountrySpec(Country.Argentina);
var customersFromArgentina = customerRepository.Find(spec);

Alternative way to expose specifications

An alternative way of exposing specifications is with a static class:

public static class CustomerSpecs
{
    public static Specification<Customer> FromCountry(Country country) 
    { 
        return new CustomerFromCountrySpec(country);
    }

    public static Specification<Customer> EligibleForDiscount(decimal discount)
    {
        return new AdHocSpecification<Customer>(
            c => c.IsPreferred && !c.HasDebt &&
                 c.LastPurchaseDate > DateTime.Today.AddDays(-30));
    }
}

Usage:

customerRepository.Find(
    CustomerSpecs.FromCountry(argentina) &&
    CustomerSpecs.EligibleForDiscount(3223));

Logical operations AND, OR, NOT

One of the most interesting features of LinqSpecs is that you can combine known specifications with "!", "&&" and "||" operators. For example:

var spec1 = new CustomerFromCountrySpec(Country.Argentina);
var spec2 = new CustomerPreferredSpec();
var result = customerRepository.Find(spec1 && !spec2);

This code returns all customers from Argentina that are not preferred. The & operator work as an && (AndAlso) operator. The same for | and ||.

Comparing

The result of and'ing, or'ing and negating specifications implements equality members. That's said:

// This returns true
(spec1 && spec2).Equals(spec1 && spec2);

// This returns true
(spec1 && (spec2 || !spec3)).Equals(spec1 && (spec2 || !spec3));

// This returns false, because AndAlso and OrElse are not commutable operations
(spec1 && spec2).Equals(spec2 && spec1);

This is an useful feature when you are writing Asserts in your unit tests.

AdHocSpecification

The AdHocSpecification is an alternative way to write a specification without writing a class. You should not abuse of them, and try to write those in a single place as explained above.

var spec = new AdHocSpecification<Customer>(c => c.IsPreferred && !c.HasDebt);

TrueSpecification and FalseSpecification

The TrueSpecification is satisfied by any object. The FalseSpecification is not satisfied by any object.

// This returns all customers
customerRepository.Find(new TrueSpecification<Customer>());

// This returns nothing
customerRepository.Find(new FalseSpecification<Customer>());

These specifications can be useful when you want to retrieve all items from a data source or when you are building a chain of several specifications. For example:

Specification<Customer> spec = new FalseSpecification<Customer>();
foreach (var country in countries)
    spec |= new CustomerFromCountrySpec(country);
return spec;

In-memory queries

Although LinqSpecs is targeted towards IQueryable<T> data source, it is possible to use LinqSpecs specifications for filtering IEnumerable<T> collections and also for other checks in memory:

IEnumerable<Customer> customers = ...
var spec = new CustomerFromCountrySpec(Country.Argentina);
var result = customers.Where(spec.ToExpression().Compile());

Compiling of expression tree into a delegate is a very slow operation, so it's a good idea to cache the result of a compilation for reuse if it's possible.

Supported platforms

  • .NET Standard 2.0+
  • .NET Framework 4.0+
  • .NET Core 2.0+

License

LinqSpecs is open-sourced software licensed under the Microsoft Public License (MS-PL).

Contributors

LinqSpecs was created by José F. Romaniello and Sergey Navozenko.

linqspecs's People

Contributors

grmagic avatar jfromaniello avatar navozenko avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

linqspecs's Issues

Stack overflow with Custom Spec

I've created a custom spec class similar to the "CustomerFromCountrySpec" in the README.md. When I create my custom class, within a second or two I get a stack overflow.

Here's my class:

public class CustomSpec: Specification<string>
{
        public string Name { get; set; }

        public CustomSpec(string name)
        {
            Name = name;
        }

        public override Expression<Func<string, bool>> ToExpression()
        {
           return  s => s == Name;
        }
}

Here's my test method

[Test]
public void CustomClassShouldntStackOverflow()
{
            var s = new CustomSpec("Jose");
            Assert.True(true); //Put a break point here and let it set for 5 seconds, you'll stack overflow.
}

.NET Standard supporting

There is an idea to add .NET Standard support to allow using LinqSpecs on the .NET Core. Unfortunately, the existing LinqSpecs code is not fully compatible with .NET Standard versions 1.0-1.6 because there is no SerializableAttribute in .NET Standard 1.0-1.6. All specifications in LinqSpecs are marked with the [Serializable] attribute and support binary serialization. Is it really necessary? Should we remove the [Serializable] attribute for compatibility with .NET Standard?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.