Saturday, 27 June 2015

Applying The Repository Pattern on LINQ and ADO.NET Entity Framework 4




Introduction The Repository Design Pattern

The Repository design pattern adds a layer of abstraction on top of the query layer and helps to eliminate duplicate query logic in your application's code. In his great book "Patterns of Enterprise Application Architecture", Martin Fowler defines the Repository Pattern as: "Mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects." This article takes a look at the principles of the repository pattern and discusses how it can be implemented in applications that make use of LINQ and the Entity Framework 4.0.

Pre-requisites

To use the code examples illustrated in this article, you should have any one of the following installed in your system:
  • Microsoft Visual Studio 2008
  • Microsoft Visual Studio 2010

What is the Repository Pattern?

A repository is essentially a collection of in memory domain objects. The repository pattern provides a way to provide isolation between the data access layer of your application with the presentation and business layer. In using the repository pattern, you can have persistence, ignorance and a separation of concerns in your data access code. The repository encapsulates the necessary logic to persist your domain objects in the underlying data store. In essence, you can use the repository pattern to decouple the domain model from the data access code.
Martin Fowler states: "A Repository mediates between the domain and data mapping layers, acting like an in-memory domain object collection. Client objects construct query specifications declaratively and submit them to Repository for satisfaction. Objects can be added to and removed from the Repository, as they can from a simple collection of objects, and the mapping code encapsulated by the Repository will carry out the appropriate operations behind the scenes. Conceptually, a Repository encapsulates the set of objects persisted in a data store and the operations performed over them, providing a more object-oriented view of the persistence layer. Repository also supports the objective of achieving a clean separation and one-way dependency between the domain and data mapping layers." Reference:http://martinfowler.com/eaaCatalog/repository.html
The following code snippet illustrates how a repository interface is designed:
  1. public interface IStudentRepository
  2.    {
  3.        Student GetByID(int studentID);
  4.        Student Load(int studentID);
  5.        void Save(Student student);
  6.        void Delete(Student student);
  7.    }
Similar to the interface for the Student Repository, you can have interfaces for Product and Order Repositories as shown below:
  1. public interface IProductRepository
  2.    {
  3.        Product GetByID(int productID);
  4.        Product Load(int productID);
  5.        void Save(Product product);
  6.        void Delete(Product product);
  7.    }
  8. public interface IOrderRepository
  9.    {
  10.        Order GetByID(int orderID);
  11.        Order Load(int orderID);
  12.        void Save(Order order);
  13.        void Delete(Order order);
  14.    }
You can now use generics to generalize this interface. Here's a generic implementation of the interface for any repositories of this kind.
  1. public interface IRepository<T>
  2. {
  3.    T GetById(int id);
  4.    T Load(int id);
  5.    void Save(T entity);
  6.    void Delete(T entity);
  7. }

Designing a LINQ Repository

To implement the repository pattern for LINQ, you would first need to define the interface that would contain the declaration of all the methods you would want in your Repository.
The following interface shows how you can use the repository pattern in LINQ:
  1. public interface IRepository<T> where T : class
  2.    {
  3.        IQueryable<T> GetAll();
  4.        void InsertOnSubmit(T entity);
  5.        void DeleteOnSubmit(T entity);
  6.        void SubmitChanges();
  7.    }
You can then use your repository to encapsulate the way storage, retrieval and query would be accomplished in your data access code using the LINQ data context. The IRepository interface is implemented by the repository class as shown in the code listing below:


  1. public class Repository<T> : IRepository<T> where T : class
  2.    {
  3.        public DataContext Context
  4.        {
  5.            get;
  6.            set;
  7.        }
  8.        public virtual IQueryable<T> GetAll()
  9.        {
  10.            return Context.GetTable<T>();
  11.        }
  12.        public virtual void InsertOnSubmit(T entity)
  13.        {
  14.            GetTable().InsertOnSubmit(entity);
  15.        }
  16.        public virtual void DeleteOnSubmit(T entity)
  17.        {
  18.            GetTable().DeleteOnSubmit(entity);
  19.        }
  20.        public virtual void SubmitChanges()
  21.        {
  22.            Context.SubmitChanges();
  23.        }
  24.        public virtual ITable GetTable()
  25.        {
  26.            return Context.GetTable<T>();
  27.       
  28. }
  29.    }

Designing a Repository for Entity Framework 4

The ADO.NET Entity Framework is an extended Object Relational Mapping (ORM) that can be used to abstract the object model of an application from its relational or logical model. The ADO.NET Entity Framework was designed by Microsoft to objectify your application's data and in doing so; isolate the logical or relational model of your application from the object model. ADO.NET Entity Framework 4.0 ships with Microsoft Visual Studio 2010 and provides a lot of new features and enhancements.
To implement the repository pattern for Entity Framework, you can start by defining an interface as shown below:
  1. public interface IRepository&lt;T&gt;
  2. {
  3. &nbsp;&nbsp;&nbsp;T GetById(int id);
  4. &nbsp;&nbsp;&nbsp;T[] GetAll(); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  5. &nbsp;&nbsp;&nbsp;IQueryable&lt;T&gt; Query(Expression&lt;Func&lt;T, bool&gt;&gt; filter);
  6. &nbsp;&nbsp;&nbsp;void Save(T entity);
  7. &nbsp;&nbsp;&nbsp;void Delete(T entity);
  8. }
Now that the interface has been defined, you can use it to implement your repository classes. The following code listing shows how you can implement the StudentRepository class:
  1. public class StudentRepository : IRepository<Student>, IDisposable
  2. {
  3.    private MyEntities _context;        
  4.    public StudentRepository()
  5.    {            
  6.        _context = new MyEntities();
  7.    }
  8.    public Student GetById(int id)
  9.    {
  10.        return _context.Students.
  11.            Where(s => s.StudentID == id).
  12.            FirstOrDefault();
  13.    }
  14.    public Student[] GetAll()
  15.    {
  16.        return _context.Students.ToArray();
  17.    }
  18.    public IQueryable<Student> Query(Expression<Func<Student, bool>> filter)
  19.    {
  20.        return _context.Students.Where(filter);
  21.    }
  22.    public void Save(Student student)
  23.    {
  24.       //Necessary code to persist a student record to the database
  25.    }
  26.    public void Delete(Student student)
  27.    {
  28.       //Necessary code to delete a student record
  29.    }
  30.    public void Dispose()
  31.    {
  32.        if (_context != null)
  33.        {
  34.            _context.Dispose();
  35.        }
  36.     
  37.       GC.SuppressFinalize(this);
  38.    }
  39. }

Summary

The repository pattern provides a simple way to encapsulate the data access code in your application and promotes testable code, reusable code modules and separation of concerns between the data access logic and application's domain logic. In essence, the repository pattern promotes testability and usage of dependency injection, reduces the coupling or cohesion amongst the data access components and the application's domain model and abstracts the way data access code is written in your applications. In this article we discussed what the repository pattern is and how it can be implemented on top of LINQ and Entity Framework in your applications. Happy reading!

No comments:

Post a Comment

Angular Tutorial (Update to Angular 7)

As Angular 7 has just been released a few days ago. This tutorial is updated to show you how to create an Angular 7 project and the new fe...