Implementing an architecture with ASP.NET MVC (Part 4) – data access

Continuing on from part3 – the business layer. In this post the focus is on data access. In part 3, I created an interface called “ICustomerRepository” and a class “CustomerRepository” which will change to actually do something. Using the repository interface, our business code can interact with it without being coupled to the technology that is used to communicate with the data store.

This post is part of a series of posts about creating an architecture when creating a line of business application with ASP.NET MVC. The business and persistence layers have nothing to do with ASP.NET MVC or any other UI technology so this approach is relevant to any .net application. The next and last post of the series will be placing the business and persistence behind a WCF endpoint.

What technology?

We have many choices in the data access area. You could have either a ODBMS or a RDBMS. If you are using RDBMS than is a pretty good assumption to say you are using MS SQL server. So what choices do you have:

ADO.NET – Simple to understand, but as your application grows you will end up writing the same code over and over unless you create your own abstraction over the top. You have to write the SQL yourself, which means you will end up with many stored procedures (sprocs). On a positive note, you have control of the SQL and you can use sprocs as a API to your database. You can shape the result set of data in your sproc so its easier to handle in the application. This is the traditional approach, personally i had been using this approach since SQL 7.0 before .NET and also back in .NET 1.0 and 1.1. days. From experience, you do write more code mapping the results of the sproc to your classes. Other ways of using ADO.NET would be to provide the SQL inline with .NET code or use typed DataSets (poor mans attempt of ORM), but these are just wrong on many counts.

Object Relational Mappers (ORMs)

ORM’s have been around for years and have got more popular of the last 2-3 years in .net world. You have two types of ORMs, the first type are based on the Active Record pattern and the next type based on the Data Mapper pattern.  The active Record pattern in short is where your database table and domain class have a 1 to 1 mapping. So your domain classes mirror the database. Works well when you have a good database schema. The Data mapper is where your domains class are different from the data tables. Their are lots of ORMs available, here is a summary I the ones I know well.

NHibernate – IMHO the most powerful ORM to date, supports the data mapping pattern, been around for a while and got a big community around it and a number of tools like NHProf and Fluent NHibernate that improve the experience. Being as powerful as it is, its a bigger learning curve. It has it own methods for querying data using HQL, detached criteria as well as Linq (not fully implemented). Also NH supports many different RDBMS’s. Negatives for me are, session management and that it requires initialising when you start your application. By default uses XML mapping files (I hate writing XML, but enjoy writing XAML. Work that one out). Need a handful of DLL’s that you need to ship with your application.

Castle ActiveRecord – Personal favourite. Built on top of NHIbernate and supports the Active Record Pattern. You add attributes to your classes and properties to set up your mapping. Its simple, but you have the power of nhibernate under the hood if you need it. The session management is simplified, still requires initialisation when your application starts.  The ActiveRecordMediator is so simple to use. Negatives are that it requires shipping the same DLL’s that nhibernate needs plus the the castle ones. Borrows the querying functionality from nhibernate.

Linq for SQL (DLINQ) – Very simple to use, supports the Active Record pattern. Can you attributes or XML to define the mapping. Does come with a designer/SQL metal. Personally i hand craft my domain classes as the designer gives you a lot of boilerplate code that in more cases in not needed, plus i model the domain first and not the database. Its built into the .NET framework so no external DLL’s to manage. No session management, the data contexts only needs a connection string. The data context uses transactions by default. The only querying mechanism is Linq which is fully implemented. Negatives are: Limited to SQL server and SQL CE, have to include properties in your classes that relate to foreign keys in the db.

Linq for Entities – (ADO.NET Entity framework) – Waiting for the next version of this, as the current version is data driven instead of domain driven. So for me its not an option at the moment.

Object Database Management Systems (ODBMS)

I only have experience in using one ODBMS being db4o. Using an object database in a change in mindset and is not that common across the .NET developer community, although products like db4o does have a massive community across .net and java developers. I think the reason for slow uptake is down to the fact that RDBMS have been around for 30 odd years and they have got better and vendors have changed their products to keep supporting the current market trends like XML.

Db4o – Really easy to use, requires a tiny amount of code. Uses a file either locally or on a remote server. No mapping required, you use OO in your domain so why not store it OO in the database. Supports Linq and also has other ways to query the database. Great documentation and support. Negatives… wish it was more a mainstream so i wouldn’t have to use RDBMS’s any more.

While developing a project with Db4o, you realise that you don’t think rows in a table or association tables. And what is even better, when you already have a database in place that contains data and you make changes to your classes like adding properties, do you need a database migration script? no. Some smart stuff inside db4o knows that the type has changed an handles it. You don’t lose data, it just works. This is a big positive for me. When using a RDBMS, tracking database changes in development is a pain and you need a process in place not only for development but when you deploy to other environments. if you have a bug in script it stops you from deploying your release as you need keep your scripts in sync with your code. Needless to say, when managing SQL scripts you need to make changes within a transaction so it can rollback in the event of failure and you must also write your scripts so they can be run more than once. With Db4o its a non-issue, no scripts, no process, no problems.

So what technology?

Ok enough rumbling. With my agile head on. I will chose the simplest option, which i believe its db4o.

Implementing the Repository

At the end of part 3, I created a domain class called “Customer”, the ICustomerRepository interface and a concrete implementation called CustomerRepository.

Using db4o

  1. So if you haven’t got db4o you can download the msi from here. I am using version 7.4 for .net 3.5.
  2. In the Web.Business project, add references to:
    • Db4objects.Db4o.dll
    • Db4objects.Db4o.Linq.dll
    • System.Configuration
  3. One difference between using SQL server and db4o is the connection lifetime, in SQL server connections are opened and closed as quickly as possible and the connection is returned to a pool (if configured to). In db4o, this works differently. When you start your application you open the connection and keep it open until the application ends.  Their are a few ways to do this, one of the common approaches i see in web applications that require initialising a database component like nhibernate and Castle ActiveRecord is that in the Global.asax, its configured in the Application_Start() method. I think this stinks, why does UI application need to know about the persistence. My preferred way is to make it happen where its needed. Because i need to ensure the lifetime is the same as the application, I use a singleton to hold the reference. Here is that class.
    using System;
    using System.Configuration;
    using Db4objects.Db4o;
    
    namespace Web.Business.Persistence.Db4o
    {
        internal class DatabaseContext : IDisposable
        {
            private static DatabaseContext context;
    
            private IObjectContainer database;
    
            static DatabaseContext()
            {
                context = new DatabaseContext();
            }
    
            private DatabaseContext()
            {
                database = Db4oFactory.OpenFile(Db4oFactory.NewConfiguration(),
                    ConfigurationManager.AppSettings["DatabaseFileName"]);
            }
    
            public void Dispose()
            {
                database.Close();
            }
    
            public static DatabaseContext Current
            {
                get { return context; }
            }
    
            public IObjectContainer Client
            {
                get { return database; }
            }
        }
    }
  4. I have added an application setting into the web.config called “DatabaseFileName” which as you might as guessed is the path to the db4o database file.<appSettings><add key=”DatabaseFileName” value=”C:\Web\WebDb.yap”/>

    </appSettings>

  5. Now to make the CustomerRepository use the DatabaseContext to fetch the data. The finished code looks like this.
    using System.Collections.Generic;
    using System.Linq;
    using Db4objects.Db4o.Linq;
    using Web.Business.Domain;
    
    namespace Web.Business.Persistence
    {
        internal class CustomerRepository : ICustomerRepository
        {
            public List<Customer> FindAll()
            {
                return (from Customer customer in DatabaseContext.Current.Client select customer).ToList();
            }
        }
    }
  6. That’s it, done. Only the database is empty. Ideally in the real world you might have screens in your application that you can use to populate the database. As we don’t, i have created a test that can be run to insert data in the database.
    using NUnit.Framework;
    using Web.Business.Domain;
    using Web.Business.Persistence;
    
    namespace Web.Business.Specs
    {
        [TestFixture]
        [Category("Integration")]
        public class DataIntegrationFixture
        {
            [Test]
            [Explicit]
            public void PopulateCustomers()
            {
                Customer customer = new Customer
                {
                    AccountManagerName = "Mr A Manager",
                    AccountNumber = "ABC123",
                    City = "Some big city",
                    Country = "UK",
                    Name = "Big city customer"
                };
    
                DatabaseContext.Current.Client.Store(customer);
            }
        }
    }

If you run the application, the data will be pulled from the database and displayed in the view. If this was a real application, i would create an generic abstract EntityRepository class that took a domain class as its generic type. I would make this base class use the DatabaseContext and that way i would not be repeating code.

Advertisements

Creating Fluent finders and repositories part 1

Introduction

This is the first post of this series about implementing fluent finders and repositories, I am going to expand my current repository and finder implementation which is explained here. I recommend that you read this post (precursor) as this series continues on from this post and the code examples.

The objectives for this series are:

  • Create a fluent interface on the finders
    • Chain the find methods so that you can find on more than one method (method chaining).
    • Create an interface for sorting.
    • Create an interface for paginating the results.
  • Allow a service request (coarse grain) to be mapped to a specific fluent-interface call.
    • Based on information provided to a service as a request object, determine the right strategy for satisfying the request.
    • Execute the relevant strategy to perform the relevant queries
    • Return the query results to service method that was called.
    • The service method will return results as a response object.
  • Drive out these behaviours using TDD/BDD.

The outcome of this work will allow you write something like:

repository.find.ByThis(somevalue).AndFind.ByThat(someOtherValue).SortBy(aField, InAscendingOrder).Paginate.WithPageSize(10).ShowPage(1);

Before I start, one of the main benefits of a fluent interface is that you create an API that guides and limits the decisions that can be expressed in a logical order. So the interface needs to limit the options as the expression flows, which ultimately means you need to plan out the branching and the interfaces for each branch and decisions to ensure that public interface is meaningful to its context.

Table of Contents

Precursor

Part 1  (this post)

  • Refactoring the existing interfaces to provide interface segregation.
  • The Query Command
  • Method Routing
  • Method Chaining

Refactoring

Following on from the precursor, I need to stop my “IApplicationUserFinder” from implementing the “IEntityFinder” interface. The reason for this is the the  “IEntityFinder” interface exposes a property called DataSource. The published Fluent interface will want to expose the Find methods but not the DataSource property. So a bit of interface segregation is needed here to expose the right interface to the relevant consumer. While doing this refactoring, I decided that the name of the “IEntityFinder” is not right so I have renamed it to “IQueryableDataStore”. Although I have changed these interfaces around my concrete class  ApplicationUserFinder still need to implement both. So I have created yet another interface called “IQueryableApplicationUserFinder” which implements the “IQueryableDataStore” and “IApplicationUserFinder” interfaces. Now the ApplicationUserFinder class just implements IQueryableApplicationUserFinder. If I have scrambled your brain up, hopefully the code snipets below will make things clear.

    public interface IQueryableDataStore where Entity : EntityBase // was IEntityFinder
    {
        IQueryable DataSource { get; set; }
    }
...
    public interface IQueryableApplicationUserFinder :
        IApplicationUserFinder,
        IQueryableDataStore
    {
    }
...
 public class ApplicationUserFinder : IQueryableApplicationUserFinder
...

Now, how is this used. The ApplicationUserFinder is injected into the ApplicationUserRepository and then exposed via a getter (all by interfaces).  With the “IQueryableApplicationUserFinder” now in play, here is the revised code snippet for the repository (remember to change your IoC container to accommodate these changes).

    public class ApplicationUserRepository : EntityRepository,
        IApplicationUserRepository
    {
        private readonly IQueryableApplicationUserFinder finder;

        public ApplicationUserRepository(IPersistanceRepository repository,
            IQueryableApplicationUserFinder finder) : base(repository)
        {
            this.finder = finder;

            this.finder.DataSource = Query();
        }

        public IApplicationUserFinder Find
        {
            get { return finder; }
        }
    }

At this point, all my unit tests pass and application runs the same as it did before this refactoring.

The Query Command

Regardless of the expression that you can write using the fluent-interface, it needs  an end at some point. The Query Command objects is responsible for executing the query and return the result. I am using “Linq for objects” to write my queries and passing an IQueryable around under the covers, the execution of the queries is deferred until a method is called on it like “ToList()”. Calling the “ToList()” method will execute the underlying query.  I have  created a command object (based on the command pattern) to expose an “Execute” method that is going to return an IEnumerable<Entity>. The reason for returning “IEnumerable<Entity>” is that you have a vast about of extension methods that you use to execute the query. For example “ToList()” and “FirstOrDefault”. We can create the Query Command now and integrate it into the fluent-interface later with out much effort.

    public interface IQueryCommand where Entity : EntityBase
    {
        IEnumerable Execute();
    }

    public class QueryCommand : IQueryCommand
    {
        private readonly IQueryableDataStore queryableDataStore;

        public QueryCommand(IQueryableDataStore queryableDataStore)
        {
            this.queryableDataStore = queryableDataStore;
        }

        public IEnumerable Execute()
        {
            return queryableDataStore.DataSource.AsEnumerable();
        }
    }

So how can the fluent-interface get to this endpoint? Answer: we need an object to return it, so we can call it. I have defined this as “MethodRouter”.

Method Router

The method router exposes the actions that could be performed after a find method is called. As this is based on my previous post Implementing the Repository and Finder Pattern, I am going to change the original unit tests to drive out the method router. Here is the original specification for the “ApplicationUserFinder” class.

    [TestFixture]
    public class When_executing_queries_against_application_users
    {
        private ApplicationUserFinder finder; // subject under test

        [SetUp]
        public void Setup()
        {
            finder = new ApplicationUserFinder();

            finder.DataSource = GetStubbedCollection();
        }

        [Test]
        public void Should_return_a_user_by_login_name_when_supplied_a_known_login_name()
        {
            ApplicationUser result = finder.ByLoginName("Test.User3");

            Assert.That(result.LastName, Is.EqualTo("User3"));
        }

        [Test]
        public void Should_return_a_user_by_token()
        {
            ApplicationUser result = finder.ByToken(Guid.Empty);

            Assert.That(result.LastName, Is.EqualTo("User2"));
        }

        [Test]
        [ExpectedException(typeof(ArgumentNullException))]
        public void Should_fail_if_supplied_null_login_name()
        {
            IQueryable users = GetStubbedCollection();

            ApplicationUser result = finder.ByLoginName(null);
        }

        private IQueryable GetStubbedCollection()
        {
            List users = new List
            {
                new ApplicationUser { FirstName = "Test", LastName = "User1", LoginName="Test.User1", Token = Guid.NewGuid() },
                new ApplicationUser { FirstName = "Test", LastName = "User2", LoginName="Test.User2", Token = Guid.Empty},
                new ApplicationUser { FirstName = "Test", LastName = "User3", LoginName="Test.User3", Token = Guid.NewGuid()},
                new ApplicationUser { FirstName = "Test", LastName = "User4", LoginName="Test.User4", Token = Guid.NewGuid()},
                new ApplicationUser { FirstName = "Test", LastName = "User5", LoginName="Test.User5", Token = Guid.NewGuid()}
            };

            return users.AsQueryable();
        }
    }

As you can see from the above tests, each find method returns the result as a single domain entity. I now want to return an interface of the Method Router instead. The Method Router at point will expose the QueryCommand so that I still execute the queries and keep the code in a “close to working” state at all times.

To start with, I defined the MethodRouter interface “IApplicationUserFinderActions”

    public interface IApplicationUserFinderRouter
    {
        IQueryCommand Output { get; }
    }

Now, I need to change the return types in the IApplicationUserFinder to now return the IApplicationUserFinderRouter instead.

    public interface IApplicationUserFinder
    {
        IApplicationUserFinderRouter ByLoginName(string loginName);
        IApplicationUserFinderRouter ByToken(Guid token);
    }

At this point, things a little broken, so I need to change the concrete ApplicationUserFinder class to implement the changes made to the interface. To do this the concrete finder will need to know about the Method Router class. The method Router’s responsibility is to act as a hub to link object instances together. With this in mind, the MethodRouter class will need to know about the finder and the QueryCommand class. Still being mindful of the fluent interface and members it exposes, I need to ensure that the QueryCommand knows about the IQuerable instance held in the finder without coupling the objects together. To achieve this, I going to use the same technique I used in the Refactoring effort being the i return different interfaces to different parties. I have created another interface “IFindableApplicationUserFinderRouter” that implements IApplicationUserFinderRouter with an additional member.

Here is the new interface

    public interface IFindableApplicationUserFinderRouter
        : IApplicationUserFinderRouter
    {
        IQueryableApplicationUserFinder Finder { get; set; }
    }

Here is the concrete class ApplicationUserFinderRouter at this point.

    public class ApplicationUserFinderRouter : IFindableApplicationUserFinderRouter
    {
        private IQueryCommand queryCommand;

        public IQueryableApplicationUserFinder Finder { get; set;}

        public IQueryCommand Output
        {
            get
            {
                if (queryCommand == null)
                {
                    queryCommand = new QueryCommand(Finder);
                }

                return queryCommand;
            }
        }
    }

Here is the changed ApplicationUserFinder

    public class ApplicationUserFinder : IQueryableApplicationUserFinder
    {
        private readonly IFindableApplicationUserFinderRouter router;
        private IQueryable users;

	
        public ApplicationUserFinder(IFindableApplicationUserFinderRouter router)
        {
            this.router = router;
            this.actions.Finder = this;
        }
	

        public IQueryable DataSource
        {
            get { return users; }
            set { users = value; }
        }

        public IApplicationUserFinderRouter ByLoginName(string loginName)
        {
            if (string.IsNullOrEmpty(loginName))
            {
                throw new ArgumentNullException("loginName");
            }

	    
            users.Where(u => u.LoginName == loginName).FirstOrDefault();

            return router;
        }

        public IApplicationUserFinderRouter ByToken(Guid token)
        {
            users.Where(u => u.Token == token).FirstOrDefault();

		
            return router;
        }
    }

Here is a snippet of how one of the unit tests is looking.

	[SetUp]
        public void Setup()
        {
            router = MockRepository.GenerateStub();

            finder = new ApplicationUserFinder(router);

            finder.DataSource = GetStubbedCollection();
        }

        [Test]
        public void Should_return_a_user_by_login_name_when_supplied_a_known_login_name()
        {
            ApplicationUser result = finder.ByLoginName("Test.User3").Output.Execute().FirstOrDefault();

            Assert.That(result.LastName, Is.EqualTo("User3"));
        }

At this stage is hard to see the advantage of this apart from separating out code. The next step is to allow the find methods to be chained together (method chaining).

Method Chaining

The IApplicationUserFinderRouter interface is going to allow the finder to be returned from a property. This is pretty simple stuff. Below is the interface with the new property and the concrete class implementing this addition member.

    public interface IApplicationUserFinderRouter
    {
        IQueryCommand Output { get; }
        IApplicationUserFinder AndFind { get; }
    }

    public class ApplicationUserFinderRouter : IFindableApplicationUserFinderRouter
    {
        private IQueryCommand queryCommand;

        public IQueryableApplicationUserFinder Finder { get; set;}

        public IQueryCommand Output
        {
            get
            {
                if (queryCommand == null)
                {
                    queryCommand = new QueryCommand(Finder);
                }

                return queryCommand;
            }
        }
	
        public IApplicationUserFinder AndFind
        {
            get { return Finder; }
        }
    }

This now allows the find methods to be chained so you can write the following code

        [Test]
        public void Should_return_a_user_when_finding_by_Login_name_and_token()
        {
            ApplicationUser result = repository
                .Find.ByToken(Guid.Empty)
                .AndFind.ByLoginName("Test.User2")
                .Output.Execute().FirstOrDefault();

            Assert.That(result.LastName, Is.EqualTo("User2"));
        }

That concludes this post, the next part of this series will cover paginating the results returned from the underlying query.

Implementing the Repository and Finder patterns

Introduction

Over the last year I have been developing my own application using Domain Driven Design (DDD). I am also working on products in my day job that uses DDD. In the last month, myself and my fellow developers that I work with, went on a little journey to find the right way to implement the repository pattern including queries. My fellow devs and I wanted a solution to achieve the following goals:

  • A solid OO approach that was not bound to a specific technology. Meaning that we could develop this in C# or Java or what ever language.
  • No leaky abstraction. For example, we are using nHibernate at the moment, but in the future we might choose to use a different Object Relational Mapper (ORM). We don’t want our Repository or Finder interface to expose Nhibernate interfaces like “ISession” or “ICriteria”.
  • A repository per aggregate root.
  • No code duplication
  • Fully testable, driven out by our unit tests and me able to mock out the dependancies.
  • Friendly to our Inversion of Control (IoC) framework (ninject, spring.net and castle Windsor etc)
  • Provide a fluent interface to our repositories.

None of us are new to the Repository pattern or ways to implement query objects, so we all have ideas and existing code for tackling this. Combined we come up with this.

In my own application, my implementation used extension methods, its worked well, but because extension methods are static, i had no way of mocking them out  with Rhino mocks. This was not a showstopper, but meant that when i was writing unit tests in my service layer for example i have to set up the data to satisfy the logic in the extension methods.

Throughout the rest of this post, i will be using code from my own application.

The desired result


Here is an example of how we intent to use our repositories:


ApplicationUser user = applicationUserRepository
    .Find.ByLoginName(request.LoginName);

As you can see the repository has a find property on it that exposes a  ByLoginName method that takes a string argument and returns a single ApplicationUser object.

Entity Implementation


The ApplicationUser is a Entity, all of my Entities inherit from a base class called EntityBase:

public abstract class EntityBase
{
    private int id; 

    protected EntityBase() : this(0) { } 

    protected EntityBase(int id)
    {
        this.id = id;
    } 

    public int Id
    {
        get { return this.id; }
    } 

    public abstract bool IsValid();

    ...
}

Not much to it this, all my entities have an identity and i want all my entities to be able to state if the data they contain is valid

Repository Implementation

All of my repositories extend a base IRepository interface.

public interface IRepository<T> where T : EntityBase
{
    T Get(int id);
    void Save(T entity);
}

As you can see the generic type is constrained by the EntityBase type. The IRepository interface is not used directly outside of my repository layer, but is extended by the typed Repository interfaces:

public interface IApplicationUserRepository : IRepository<ApplicationUser>
{
    IApplicationUserFinder Find { get; }
}

In my application, I use dependency injection so my repositories are injected using the typed interface.  IApplicationUserRepository has one member being the Finder interface (more on that below).

One of my objectives was to remove duplicate code, in my effort to do this, i have an abstract class in which all my repositories inherit from.

public abstract class EntityRepository<T> : IRepository<T> where T : EntityBase
{
    protected readonly IPersistanceRepository repository;

    public EntityRepository(IPersistanceRepository repository)
    {
       this.repository = repository;
    }     

    public virtual T Get(int id)
    {
       return repository.Get<T>(id);
    } 

    public virtual void Save(T entity)
    {
        if (entity == null)
        {
            throw new ArgumentNullException("entity");
        } 

        if (entity.IsValid())
        {
             repository.Save(entity);
        }
    } 

     protected IQueryable<T> Query()
     {
         return repository.Query<T>();
     }

 }

This class must be supplied an instance of IPersistanceRepository.  Here is the IPersistanceRepository interface

public interface IPersistanceRepository
{
    T Get<T>(int id);
    void Save<T>(T entity);
    IQueryable<T> Query<T>();
}

A concrete implementation of the  IPersistanceRepository interface is the technology / ORM specific stuff. I am using NHibernate 2.0, so my concrete implementation is called “NHibernateRepository”. By using the IPersistanceRepository interface i am keeping the specifics abstracted away inside the concrete class. I have been able to successfully swap my IPersistanceRepository instance from NHibernate to a DB4o implementation with ease and no effect to my repositories.

Finder Implementation

Like the IRepository interface is used as a base interface, i also have a base IEntityFinder interface which again is not directly used outside of my repository layer.

public interface IEntityFinder<T> where T : EntityBase
{
    IQueryable<T> DataSource { set; }
}

As you can see, the interface has a DataSource property of IQueryable, the reason for this is that I am using System.Linq in my project which I will come onto later. But its purpose is to give the Finder a datasource. Now for the IApplicationUserFinder interface.

public interface IApplicationUserFinder : IEntityFinder<ApplicationUser>
{
    ApplicationUser ByLoginName(string loginName);

    ApplicationUser ByToken(Guid token);
}

The typed Repository

Now for my implementation of my typed Repository.

public class ApplicationUserRepository : EntityRepository<ApplicationUser>, IApplicationUserRepository
{
    private readonly IApplicationUserFinder finder; 

    public ApplicationUserRepository(IPersistanceRepository repository, IApplicationUserFinder finder)
        : base(repository)
    {
        this.finder = finder; 

        this.finder.DataSource = Query();
    } 

    public IApplicationUserFinder Find
    {
        get { return finder; }
    }
}

This repository derives from EntityRepository and implements IApplicationUserRepository. Its constucted with its dependencies being injected. The Finder instance has it datasource set to IQuerable<ApplicationUser>.

The typed finder

using System.Collections.Generic;
using System.Linq;

public class ApplicationUserFinder : IApplicationUserFinder
{
    private IQueryable<ApplicationUser> users; 

    public IQueryable<ApplicationUser> DataSource
    {
        set { users = value; }
    } 

    public ApplicationUser ByLoginName(string loginName)
    {
        if (string.IsNullOrEmpty(loginName))
        {
            throw new ArgumentNullException("loginName");
        } 

        return users.Where(u => u.LoginName == loginName).FirstOrDefault();
    } 

    public ApplicationUser ByToken(Guid token)
    {
        return users.Where(u => u.Token == token).FirstOrDefault();
    }
}

What do we have then

We have our entity, repository and Finder created. The repository and Finder have typed interfaces, which means i can wire these up in my IoC container. My IEntityFinder interface sort of went against my goal of no leaky abstraction as its using System.Linq, but i think i can live with myself. By having my finder implement an interface i could have different concrete implementations.

My finder is returning a single instance of ApplicationUser. I could have finder methods that return Iquerable that allows for method chaining etc. Plus i have not allowed for “And”, “Or” or “Not” as that is a different topic. But i have a base to work on.

nibernate repository

To be more code complete here is a snippet of my NHibernate repository that returns the initial query. I am using nhibernate 2.0 with nhibernate.linq.

    using System.Linq;
    using NHibernate;
    using NHibernate.Linq;

    public class NHibernateRepository  : IPersistanceRepository
    {
        private readonly ISessionLocator sessionLocator;

        public NHibernateRepository(ISessionLocator sessionLocator)
        {
            this.sessionLocator = sessionLocator;
        }

        public T Get<T>(int id)
        {
            ISession session = sessionLocator.ActiveSession();

            return session.Get(id);
        }

        public void Save<T>(T entity)
        {
             ...
        }

        public IQueryable<T> Query<T>()
        {
            var qry = from t in sessionLocator.ActiveSession().Linq()
                      select t;

            return qry.AsQueryable();
        }
    }

The beauty of this that the NHibernate specific code is in one place, my repositories and finders have no knowledge of nhibernate. In my finders, i am using linq for objects and lambda’s for my logic. Because i am using IQuerable, i can build up the query through my finders and the execution is deferred until i call a method like “ToList” or “First” etc. The queryProvider in nhibernate.linq builds the sql statement and hits the database once with the specific query.

Finally a big thank you to Neil Martin and Tim Escott for their involvement on this. Please read this post “Creating Fluent finders and repositories part 1 which continues from this post.