255
CHAPTER 6 | Tackle Business Complexity in a Microservice with DDD and CQRS Patterns
The following specification loads a single basket entity given either the basket’s ID or the ID of the
buyer to whom the basket belongs. It will
eagerly load
the basket’s
Items
collection.
// SAMPLE QUERY SPECIFICATION IMPLEMENTATION
public
class
BasketWithItemsSpecification : BaseSpecification
{
public
BasketWithItemsSpecification
(
int
basketId)
:
base
(b => b.
Id
== basketId)
{
AddInclude
(b => b.
Items
);
}
public
BasketWithItemsSpecification
(
string
buyerId)
:
base
(b => b.
BuyerId
== buyerId)
{
AddInclude
(b => b.
Items
);
}
}
And finally, you can see below how a generic EF Repository can use such a specification to filter and
eager-load data related to a given entity type T.
// GENERIC EF REPOSITORY WITH SPECIFICATION
// https://github.com/dotnet-architecture/eShopOnWeb
public
IEnumerable
List
(ISpecification spec)
{
// fetch a Queryable that includes all expression-based includes
var
queryableResultWithIncludes = spec.
Includes
.
Aggregate
(_dbContext.
Set
().
AsQueryable
(),
(current, include) => current.
Include
(include));
// modify the IQueryable to include any string-based include statements
var
secondaryResult = spec.
IncludeStrings
.
Aggregate
(queryableResultWithIncludes,
(current, include) => current.
Include
(include));
// return the result of the query using the specification's criteria expression
return
secondaryResult
.
Where
(spec.
Criteria
)
.
AsEnumerable
();
}
In addition to encapsulating filtering logic, the specification can specify the shape of the data to be
returned, including which properties to populate.
Although we don’t recommend returning
IQueryable
from a repository, it’s perfectly fine to use them
within the repository to build up a set of results. You can see this approach used in the List method
above, which uses intermediate
IQueryable
expressions to build up the query’s list of includes before
executing the query with the specification’s criteria
on the last line.
Learn
how the specification pattern is applied in the eShopOnWeb sample
.
256
CHAPTER 6 | Tackle Business Complexity in a Microservice with DDD and CQRS Patterns
Dostları ilə paylaş: