Linq2SQL and Repository Pattern
In a recent project, we were requested to create a new web application that worked on an existing data model that was created using Linq2SQL and .NET Framework 3.5 SP1. We were asked to use best practices and tools of the trade in the new application, but how about the data model? Instead of directly using L2S, the best thing seemed to be creating a Repository pattern implementation on top of L2S and use that instead.
If you are new to repository pattern, here’s the definition from Martin Fowler‘s website: “A Repository mediates between the domain and data mapping layers, acting like an in-memory domain object collection”. One benefit it’d brings you, is that you no longer need to run your hard-to-manage, hard-to-run suite of tests (if you have any) on a real database and you can use an in-memory collection instead.
The goal here was to create an IRepository interface that:
- Should be used instead of L2S
- We’d be able to mock out
- Flexible in case of running complex queries
- Generic implementation with CRUD operations
So we came up with this interface:
public interface IRepository<T> where T : class
Next thing would be the implementation. Now the implementation is depending on a DataContext object to do the work. We also need to get the
Table<T> object from the data context to do the query over:
public class Repository<T> : IRepository<T> where T : class
With this, we can easily get our FindOne and FindMany methods going:
public virtual T FindOne(Func<T, bool> criteria)
CRUD operations are easy to do too. Just delegate the call to proper method on the data context:
public virtual void Insert(T item)
We are on top of an old data model with no authority over it and since the existing entity classes come with no layer supertype, so how can we implement the FindById method? We have no notion of what is the PrimaryKey property of the entity. Fortunately, DataContext provides us with the necessary meta data information so we find our about all kinds things such as the primary key property name:
private string GetPrimaryKeyName()
We were not using any composite keys and all the tables had a primary key, the above code might not work in some cases.
Still we need to create a
Func<T, bool> that is consisted of primary key name and value of the key to pass it to the FindOne method. With a magic touch of Expression Trees we can do so:
public virtual T FindByKey(long key)
As simple as that. In next part we’ll see how we can test our solution.