Skip to content

Instantly share code, notes, and snippets.

@dlidstrom
Created January 13, 2011 15:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dlidstrom/778028 to your computer and use it in GitHub Desktop.
Save dlidstrom/778028 to your computer and use it in GitHub Desktop.
Specification

First of all, here’s something you can do with the Specification class to reduce some of the code you have to write. Add the following methods:

public AndSpecification<TEntity> And(Expression<Func<TEntity, bool>> second)
{
    return new AndSpecification<TEntity>(this, new Specification<TEntity>(second));
}

public OrSpecification<TEntity> Or(Expression<Func<TEntity, bool>> second)
{
    return new OrSpecification<TEntity>(this, new Specification<TEntity>(second));
}

This allows you to write this:

IEnumerable<Product> products = repository.Find<Product>(
    new Specification<Product>(p => p.Price < 100).Or(p => p.Name == "Windows XP Professional"));

I think it looks nicer. Anyway, for your question I would recommend you to subclass Specification:

public class EmailExistsSpecification : Specification<Email>
{
    public EmailExistsSpecification(string email)
        : base(e => e.Email.ToUpper() == email.ToUpper())
    {
    }
}

Now you can re-use the EmailExistsSpecification in your methods. Nice huh?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment