Skip to content

Instantly share code, notes, and snippets.

@dlidstrom
Created January 15, 2011 11:00
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/780835 to your computer and use it in GitHub Desktop.
Save dlidstrom/780835 to your computer and use it in GitHub Desktop.
Specification design pattern
using System;
using System.Linq;
using System.Linq.Expressions;
using Infrastructure.Data.Extensions;
namespace Infrastructure.Data.Specification
{
public class Specification<TEntity> : ISpecification<TEntity>
{
public Specification(Expression<Func<TEntity, bool>> predicate)
{
Predicate = predicate;
}
public Specification<TEntity> And(Specification<TEntity> specification)
{
return new Specification<TEntity>(this.Predicate.And(specification.Predicate));
}
public Specification<TEntity> And(Expression<Func<TEntity, bool>> predicate)
{
return new Specification<TEntity>(this.Predicate.And(predicate));
}
public Specification<TEntity> Or(Specification<TEntity> specification)
{
return new Specification<TEntity>(this.Predicate.Or(specification.Predicate));
}
public Specification<TEntity> Or(Expression<Func<TEntity, bool>> predicate)
{
return new Specification<TEntity>(this.Predicate.Or(predicate));
}
public TEntity SatisfyingEntityFrom(IQueryable<TEntity> query)
{
return query.Where(Predicate).SingleOrDefault();
}
public IQueryable<TEntity> SatisfyingEntitiesFrom(IQueryable<TEntity> query)
{
return query.Where(Predicate);
}
public Expression<Func<TEntity, bool>> Predicate
{
get;
set;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment