我使用实体框架的规范模式来过滤从数据库中检索到的数据。我认为您可以使用相同的方法并使其适应您的需求。
您可以使用 DI 容器来注入您的规范和您可能需要的其他对象。第一步是为您的规范对象定义一个契约,如下所示:
public interface ISpecification<T> where T : class
{
Expression<Func<T, bool>> GetExpression();
bool IsSatisfiedBy(T entity);
}
一个通用的规范对象可以这样定义:
public class Specification<T> : ISpecification<T> where T : class
{
private Expression<Func<T, bool>> expression;
public Expression<Func<T, bool>> GetExpression()
{
return expression;
}
public Specification(Expression<Func<T, bool>> expression)
{
this.expression = expression;
}
public bool IsSatisfiedBy(T entity)
{
var query = (new[] { entity }).AsQueryable();
return query.Any(this.expression);
}
}
然后您可以像这样更改您的 Foo 类,因此您可以使用 DI/IoC 容器注入依赖项:
public class Foo()
{
public ISpecification<Foo> Specification
{
get;
private set;
}
public Foo(ISpecification<Foo> specification)
{
this.Specification = specification;
}
public void DoSomething()
{
if(Specification.SatisfiedBy(this))
{
//...
}
}
}
创建和使用规范:
// example - create one specification
Expression<Func<Foo, bool>> expression = ....;
ISpecification<Foo> fooSpecification = new Specification<Foo>(expression);
// using the specification with linq
var entities = dbContext.Foos.Where(fooSpecification.GetExpression());
// performing validation
var foo = new Foo{
// ....
};
if(fooSpecification.IsSatisfiedBy(foo))
{
// do something....
}
更多细节在这里:
http://ruijarimba.wordpress.com/2011/06/05/entity-framework-and-t4-generate-specification-objects-for-your-entities/