Home > Architecture and Design > Understanding Specification Pattern (with LINQ) –Part 2

Understanding Specification Pattern (with LINQ) –Part 2

I have covered the basics of Specification pattern in Part1. A specification is basically used as filters to query database and each specification filter is implemented as objects. Actually it should be also implemented as immutable objects.

If you think deeply, using specification objects as filters require that first we need to query the database to retrieve the results as list of objects. And then apply the specification filter on those list of objects. This may work for small applications but would be problem for application handling large amount of data. For example, think about a scenario where you need to apply a specification filter for customer list which may have millions of rows.

There is an implementation that can be done using double dispatch pattern. But better yet is to harness the power of LINQ and Expression Trees for efficient implementation. The idea is to use the expression tree as predicate that the specification object encapsulates.

The expression tree provides a method to translate executable code into data. The O/R mappers like Entity Framework, LLBLGen Pro and LINQ to SQL have the ability to traverse the expression tree and transform that into SQL statements. I recommend you must read the basics of Expression Tree. Now I believe you are getting a feel of how to utilize the power of expression trees.  Let us now modify the ISpecification interface that we created in Part1.

If you refer back the Part1, we have implemented the interface like this:

1

We will change the IsSatisfiedBy (to IsSatisfied) method to return an generic Expression Tree as shown below. We will also create a Specification abstract class which implements ISpecification interface.

image

We will now do necessary changes to EligibleForDiscountSpecification class.

image

Note the property setter is private. This is because as per pattern design, the specification object should be immutable.

Let us now see how to use the EligibleForDiscountSpecification. Please note that I am using AdventureWorks database for the demo. I have created EF model which consists of Product and Customer table.

image

I guess now you can understand the power of expression and how to use that with Entity Framework.

Summary

I covered how to implement Specification pattern using Expression tree and LINQ. In the next part of the series, we will expand the Specification interface to implement composite specification.  In future post, I will run through a ASP.NET MVC application which will explain how to use Repository pattern with Specification pattern.

  1. No comments yet.
  1. No trackbacks yet.

Leave a comment