NHibernate 3.0: Using LINQ Specifications in the data access layer

Exclusive offer: get 80% off this eBook here
NHibernate 3.0 Cookbook

NHibernate 3.0 Cookbook — Save 80%

Get solutions to common NHibernate problems to develop high-quality performance-critical data access applications

₨831.00    ₨166.20
by Jason Dentler | October 2010 | .NET Cookbooks Open Source Web Development

With the completion of LINQ to NHibernate for NHibernate 3.0, we can easily implement the specification pattern. In this article by Jason Dentler, author of NHibernate 3.0 Cookbook, we will see how to set up and use the specification pattern with the NHibernate repository.

 

NHibernate 3.0 Cookbook

NHibernate 3.0 Cookbook

Get solutions to common NHibernate problems to develop high-quality performance-critical data access applications

  • Master the full range of NHibernate features
  • Reduce hours of application development time and get better application architecture and performance
  • Create, maintain, and update your database structure automatically with the help of NHibernate
  • Written and tested for NHibernate 3.0 with input from the development team distilled in to easily accessible concepts and examples
  • Part of Packt's Cookbook series: each recipe is a carefully organized sequence of instructions to complete the task as efficiently as possible
        Read more about this book      

(For more resources on NHibernate, see here.)

Getting ready

Download the LinqSpecs library from http://linqspecs.codeplex.com. Copy LinqSpecs.dll from the Downloads folder to your solution's libs folder.

Complete the Setting up an NHibernate Repository recipe.

How to do it...

  1. In Eg.Core.Data and Eg.Core.Data.Impl, add a reference to LinqSpecs.dll.
  2. Add these two methods to the IRepository interface.

    IEnumerable<T> FindAll(Specification<T> specification);
    T FindOne(Specification<T> specification);

  3. Add the following three methods to NHibernateRepository:

    public IEnumerable<T> FindAll(Specification<T> specification)
    {
    var query = GetQuery(specification);
    return Transact(() => query.ToList());
    }

    public T FindOne(Specification<T> specification)
    {
    var query = GetQuery(specification);
    return Transact(() => query.SingleOrDefault());
    }

    private IQueryable<T> GetQuery(
    Specification<T> specification)
    {
    return session.Query<T>()
    .Where(specification.IsSatisfiedBy());
    }

  4. Add the following specification to Eg.Core.Data.Queries:

    public class MoviesDirectedBy : Specification<Movie>
    {

    private readonly string _director;

    public MoviesDirectedBy(string director)
    {
    _director = director;
    }

    public override
    Expression<Func<Movie, bool>> IsSatisfiedBy()
    {
    return m => m.Director == _director;
    }
    }

  5. Add another specification to Eg.Core.Data.Queries, using the following code:

    public class MoviesStarring : Specification<Movie>
    {

    private readonly string _actor;

    public MoviesStarring(string actor)
    {
    _actor = actor;
    }

    public override
    Expression<Func<Movie, bool>> IsSatisfiedBy()
    {
    return m => m.Actors.Any(a => a.Actor == _actor);
    }
    }

How it works...

The specification pattern allows us to separate the process of selecting objects from the concern of which objects to select. The repository handles selecting objects, while the specification objects are concerned only with the objects that satisfy their requirements.

In our specification objects, the IsSatisfiedBy method of the specification objects returns a LINQ expression to determine which objects to select.

In the repository, we get an IQueryable from the session, pass this LINQ expression to the Where method, and execute the LINQ query. Only the objects that satisfy the specification will be returned.

For a detailed explanation of the specification pattern, check out http://martinfowler.com/apsupp/spec.pdf.

There's more...

To use our new specifications with the repository, use the following code:

var movies = repository.FindAll(
new MoviesDirectedBy("Stephen Spielberg"));

Specification composition

We can also combine specifications to build more complex queries. For example, the following code will find all movies directed by Steven Speilberg starring Harrison Ford:

var movies = repository.FindAll(
new MoviesDirectedBy("Steven Spielberg")
& new MoviesStarring("Harrison Ford"));

This may result in expression trees that NHibernate is unable to parse. Be sure to test each combination.

Summary

In this article we covered:

  • Using LINQ Specifications in the data access layer

Further resources on this subject:


NHibernate 3.0 Cookbook Get solutions to common NHibernate problems to develop high-quality performance-critical data access applications
Published: October 2010
eBook Price: ₨831.00
Book Price: ₨1,386.00
See more
Select your format and quantity:

About the Author :


Jason Dentler

Jason Dentler grew up in the small Texas town of Mission Valley. He started tinkering with computers as a kid in the late 1980s, and all these years later, he hasn't stopped. He's worked in a few different industries. Currently, he builds really awesome software in higher education. He's an Eagle Scout and a graduate of the University of Houston – Victoria.

Books From Packt


NHibernate 2 Beginner's Guide
NHibernate 2 Beginner's Guide

WCF 4.0 Multi-tier Services Development with LINQ to Entities
WCF 4.0 Multi-tier Services Development with LINQ to Entities

ASP.NET 3.5 Application Architecture and Design
ASP.NET 3.5 Application Architecture and Design

Microsoft Windows Communication Foundation 4.0 Cookbook for Developing SOA Applications
Microsoft Windows Communication Foundation 4.0 Cookbook for Developing SOA Applications

.NET Compact Framework 3.5 Data Driven Applications
.NET Compact Framework 3.5 Data Driven Applications

Microsoft Azure: Enterprise Application Development
Microsoft Azure: Enterprise Application Development

Applied Architecture Patterns on the Microsoft Platform
Applied Architecture Patterns on the Microsoft Platform

Microsoft Windows Workflow Foundation 4.0 Cookbook
Microsoft Windows Workflow Foundation 4.0 Cookbook


Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software