This video is available to students only

Introducing Specification Pattern

In this lesson, we're going to implement Specification Pattern

Specification pattern#

Our controllers are working but they don't return the navigation properties now. Course repository just returns the Courses, while Category repository returns the Categories. As we discussed, we cannot use Include method because we're not sure of the Entity type. This is where specification pattern comes to our rescue. You can simply create a condition — for example, you want all the courses which are below $10; and pass the specification to the ListAsync method. The method will keep that specification in mind while making that query. Don't get confused, let's see how to use them.

Inside the Entity project, we need a new folder which will be called Specifications. Inside the folder, let's create an interface which will be called ISpecification. It will take a type as well so we write T inside the curly brackets. We now need to create some generic methods. Let's create an expression which will take a function. The function will take a type which is dynamic right now so we can call it T and it will return a boolean so we can call it bool. Let's name it Criteria because we are going to write a query which will ask our database what to get. For example, if we want a course with price below $10, we can write a criteria and we will get the data whenever the criteria is met. We also need to write get. Let's import everything now; Expressions using System.Linq.Expressions and System to use Func.

Now let's write our second criteria which will be equal to the Include method that we used here. This will be a List of Expression - Expression will take a function which will take an Entity and this time, it will return an object. We can call it Include - and finally the get. For List, we need to import System.Collections.Generic. This might look very confusing right now and I agree. Once we implement it using the actual expression, it will appear very straightforward.


Start a new discussion. All notification go to the author.