Wednesday, December 1, 2010

Repository Pattern - LINQ Implementation

The purpose of this article is to describe the technique I have used to implement the repository pattern in .NET applications. I will provide a brief description of the repository pattern and linq-to-sql, however, if you are unfamiliar with these technologies you should research them elsewhere. The goals of my implementation are:

  • it must be a general purpose design that can be reused for many projects
  • it must facilitate domain driven design
  • it must facilitate unit testing and testing in general
  • it must allow the domain model to avoid dependencies on infrastructure
  • it must provide strongly typed querying

 

Repository Pattern

 

The Repository Pattern, according to Martin Fowler, provides a "layer of abstraction over the mapping layer where query construction code is concentrated", to "minimize duplicate query logic". In practice it is usually a collection of data access services, grouped in a similar way to the domain model classes.

By accessing repositories via interfaces the repository pattern helps to break the dependency between the domain model and data access code. This is invaluable for unit testing because the domain model can be isolated.

I implement the repository pattern by defining one repository class for each domain model entity that requires specialized data access methods (other than the standard create, read, update and delete). If an entity does not require specialized data access methods then I will use a generic repository for that entity. A repository class contains the specialized data access methods required for its corresponding domain model entity.

The following class diagram shows an example implementation with one domain entity classes, Message. Message has a specialized repository (IMessageRepository).




Linq-to-sql

 

Linq is a strongly typed way of querying data. Linq-to-sql is a dialect of Linq that allows the querying of a Sql Server database. It also includes object / relational mapping and tools for generating domain model classes from a database schema. Linq is an excellent addition to object / relational mappings tools because it facilitates strongly typed queries, such as:

 

List<LabMessage> msgList = _genericMessageRepository.FindAll(m => m.PassCode1 == passCode1,
                          m => m.Active == (active == Active.Both ? m.Active : Convert.ToBoolean(active.GetHashCode()))).ToList();

 

 

IRepository<T>

The generic interface IRepository<T> defines the methods that are required on each repository.


public interface IRepository<T> where T : class
{
    /// <summary>
    /// Return all instances of type T.
    /// </summary>
    /// <returns></returns>
    IEnumerable<T> All();
  
    /// <summary>
    /// Return all instances of type T that match the expression exp.
    /// </summary>
    /// <param name="exp"></param>
    /// <returns></returns>
    IEnumerable<T> FindAll(Func<T, bool> exp);
  
    /// <summary>
    /// Return all instances of type T that match the expression exp.
    /// </summary>
    /// <param name="exp"></param>
    /// <returns></returns>
    IEnumerable<T> FindAll(Func<T, bool>[] exp);
  
  
    /// <summary>Returns the single entity matching the expression. 
    /// Throws an exception if there is not exactly one such entity.</summary>
    /// <param name="exp"></param><returns></returns>
    T Single(Func<T, bool> exp);
  
    /// <summary>Returns the first element satisfying the condition.</summary>
    /// <param name="exp"></param><returns></returns>
    T First(Func<T, bool> exp);
  
    /// <summary>
    /// Mark an entity to be deleted when the context is saved.
    /// </summary>
    /// <param name="entity"></param>
    void MarkForDeletion(T entity);
  
    /// <summary>
    /// Create a new instance of type T.
    /// </summary>
    /// <returns></returns>
    T CreateInstance();
  
    /// <summary>Persist the data context.</summary>
    void SaveAll();
} 

 

 

Repository<T>

IRepository<T> is implemented by a generic repository base class, Repository<T>. Repository<T> is a base implementation that provides data access functionality for all entities. If an entity (T) does not require a specialized repository then its data access will be done through Repository<T>.


public class Repository<T> : IRepository<T> 
    where T : class
{
    protected IDataContextFactory _dataContextFactory;
  
    /// <summary>
    /// Return all instances of type T.
    /// </summary>
    /// <returns></returns>
    public IEnumerable<T> All()
    {
        return GetTable;
    }
  
    /// <summary>
    /// Return all instances of type T that match the expression exp.
    /// </summary>
    /// <param name="exp"></param>
    /// <returns></returns>
    public IEnumerable<T> FindAll(Func<T, bool> exp)
    {
        return GetTable.Where<T>(exp);
    }
  
    /// <summary>
    /// Return all instances of type T that match the expression exp.
    /// </summary>
    /// <param name="exp"></param>
    /// <returns></returns>
    public IEnumerable<T> FindAll(Func<T, bool>[] exprs)
    {
        IEnumerable<T> res = GetTable.ToList<T>();
        foreach (Func<T, bool> selector in exprs)
         {
                res = res.Where<T>(selector);
         }
  
        return res;
    }
  
    /// <summary>See IRepository.</summary>
    /// <param name="exp"></param><returns></returns>
    public T Single(Func<T, bool> exp)
    {
        return GetTable.Single(exp);
    }
  
    /// <summary>See IRepository.</summary>
    /// <param name="exp"></param><returns></returns>
    public T First(Func<T, bool> exp)
    {
        return GetTable.First(exp);
    }
  
    /// <summary>See IRepository.</summary>
    /// <param name="entity"></param>
    public virtual void MarkForDeletion(T entity)
    {
        _dataContextFactory.Context.GetTable<T>().DeleteOnSubmit(entity);        
    }
  
    /// <summary>
    /// Create a new instance of type T.
    /// </summary>
    /// <returns></returns>
    public virtual T CreateInstance()
    {
        T entity = Activator.CreateInstance<T>();
        GetTable.InsertOnSubmit(entity);
        return entity;
    }
  
    /// <summary>See IRepository.</summary>
    public void SaveAll()
    {
        _dataContextFactory.SaveAll();
    }
  
    public Repository(IDataContextFactory dataContextFactory)
    {
        _dataContextFactory = dataContextFactory;
    }
    
    #region Properties
  
    private string PrimaryKeyName
    {
        get { return TableMetadata.RowType.IdentityMembers[0].Name; }
    }
  
    private System.Data.Linq.Table<T> GetTable
    {
        get { return _dataContextFactory.Context.GetTable<T>(); }
    }
  
    private System.Data.Linq.Mapping.MetaTable TableMetadata
    {
        get { return _dataContextFactory.Context.Mapping.GetTable(typeof(T)); }
    }
  
    private System.Data.Linq.Mapping.MetaType ClassMetadata
    {
        get { return _dataContextFactory.Context.Mapping.GetMetaType(typeof(T)); }
    }
  
    #endregion
}

 

IMessageRepository & MessageRepository

It is usually desirable to provide more specialised repositories for entity classes. If our domain included a Message entity we might like to have a MessageRepository with a RetrieveByNumberOfSides(int sideCount) method. Such a class would be exposed to consumers as a specialized interface IMessageRepository:

    public interface IMessageRepository: IRepository<LabMessage>
    {
       public LabMessage RetrieveByNumberOfSides(int);
    }

    public class MessageRepository: Repository<LabMessage>, IMessageRepository
    {
        public LabMessage RetrieveByNumberOfSides(int sideCount)
        {
            return FindAll(m => m.SomeProperty == sideCount);
        }
    }

 

Usage

We now have a fully functioning, decoupled repository implementation. A class might use the repositories as follows:

namespace Nuance.Veriphy.DataManager
{
    /// <summary>
    ///
    /// </summary>
    public class MessageManager
    {
        private IRepository<LabMessage> _genericMessageRepository;
        private IMessageRepository _specializedMessageRepository;

        #region Constructor

        /// <summary>
        ///
        /// </summary>
        /// <param name="genericMessageRepository"></param>
        public MessageManager(IRepository<LabMessage> genericMessageRepository)
        {
            _genericMessageRepository = genericMessageRepository;
            _specializedMessageRepository = null;
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="genericMessageRepository"></param>
        /// <param name="specializedMessageRepository"></param>
        public MessageManager(IRepository<LabMessage> genericMessageRepository, IMessageRepository specializedMessageRepository)
        {
            _genericMessageRepository = genericMessageRepository;
            _specializedMessageRepository = specializedMessageRepository;
        }
       
        #endregion

        #region Manager APIs

        /// <summary>
        ///
        /// </summary>
        /// <param name="messageId"></param>
        /// <returns></returns>
        public LabMessage GetLabMessage(int messageId)
        {
            LabMessage msg = _genericMessageRepository.Single(m => m.MessageID == messageId);
            return msg;
        }

        /// <summary>
        ///
        /// </summary>
        public List<LabMessage> GetLabMessages(DateTime startDate, DateTime endDate, Active active)
        {
            Func<LabMessage, bool>[] exprs = { m => m.CreatedOn >= startDate,
                                               m => m.CreatedOn <= endDate,
                                               m => m.Active == (active == Active.Both ? m.Active : Convert.ToBoolean(active.GetHashCode()))
                                             };

            List<LabMessage> msgList = _genericMessageRepository.FindAll(exprs).ToList();
           
            return msgList;
        }
       
        /// <summary>
        /// List LabMessages by Passcode1
        /// </summary>
        /// <param name="passCode1">Int</param>
        /// <param name="active">Enum:Active</param>
        /// <returns>List:LabMessage</returns>
        public List<LabMessage> GetLabMessages(int passCode1, Active active)
        {
            List<LabMessage> msgList = _genericMessageRepository.FindAll(m => m.PassCode1 == passCode1,
                                       m => m.Active == (active == Active.Both ? m.Active : Convert.ToBoolean(active.GetHashCode()))).ToList();


            return msgList;
        }

        #endregion
    }
}
}

Test Class:


public void Test()
        {
            IDataContextFactory idataContext = new LabMessageDataContext();
            MessageManager target = new MessageManager(new Repository<LabMessage>(idataContext));

            DateTime startDate = new DateTime(2009, 10, 09);
            DateTime endDate = new DateTime(2009, 10, 16);
            Active active = Active.Active;
            int expected = 438;
            List<LabMessage> actual;

            actual = target.GetLabMessages1(startDate, endDate, active);
            Assert.AreEqual(expected, actual.Count);
        }

Hope this helps.

Regards,
Arun Manglick 

No comments:

Post a Comment