Blog Archives

Factory Pattern

Introduction

In the previous post I described using the Repository pattern to encapsulate set of Entities. The next step is creation an class which will be responsible for creating those repositories. It will be an implementation of Factory pattern ( simplified version of Factory Method pattern).

Problem definition

The Factory Design Pattern is probably the most used design pattern in modern programming languages like Java and C#. Its aim is to create objects without exposing the instantiation logic to the client. It also refers to the newly created object through a common interface.  Another important factor is fact that we usually implement Factories using also Singleton pattern.

A singleton is a class which only allows a single instance of itself to be created, and usually gives simple access to that instance. In this post I’ll present also thread-safe implementation of this pattern.

Solution

Let me remind a generic implementation of Repository pattern which I presented in the previous post.

interface IRepository<T> where T : class
{
   IEnumerable<T> GetAll();
   IEnumerable<T> GetByQuery(Expression<Func<T, bool>> where);
   T GetByID(int ID)
   void Delete(T entity);
   void Add(T entity);
}

The factory we want to create has to fulfil several requierments:

  • It must contain generic function creating repositories
  • The repositories has to be refereed through IRepository<T> interface
  • It must be singleton
  • It must be thread-safe

First of all I’ll implement the Factory satisfying two first conditions – simple class with one function for creating Repositories.

public class RepositoryFactory
{
   public IRepository<T> GetRepositoryInstance<T, TRepository>()
      where TRepository : IRepository<T>, new() where T : System.Data.Objects.DataClasses.EntityObject
   {
      return new TRepository();
   }
}

As You can see it is rather simple. The function creating classes is an generic function which takes two types – the first one is a type of Entity which repository we are going to create, and the second one is a type of Repository we are going to create. As You can see, despite the fact that we create objects of concrete repository the function is returning IRepository<T>. This implementation is rather simple but contains one big drawback – someone can create many objects of Factory class what is absolutely not necessary. So let’s make our Factory a singleton.

public sealed class RepositoryFactory
{
   private static RepositoryFactory _instance;

   public static RepositoryFactory Instance
   {
      get { return _instance ?? (_instance = new RepositoryFactory()); }
   }

   private RepositoryFactory()
   {
   }

   public IRepository<T> GetRepositoryInstance<T, TRepository>()
      where TRepository : IRepository<T>, new() where T : System.Data.Objects.DataClasses.EntityObject
   {
      return new TRepository();
   }
}

The above solution presents one of the most popular Singleton Design Pattern implementation. The constructor of class is private so we cannot just create an Factory object. The access to object is get by an Instance property ( which, BTW, contain also so Lazy Loading features – the object is created only when it is need, not during program start ) which can return only existing object of this class. Only this instance is able to invoke a function which creates repositories.

As hinted at before, the above is not thread-safe. Two different threads could both have evaluated the test if (instance==null) and found it to be true, then both create instances, which violates the singleton pattern. Note that in fact the instance may already have been created before the expression is evaluated, but the memory model doesn’t guarantee that the new value of instance will be seen by other threads unless suitablememory barriers have been passed. Below solution presents simple thread-safe mechanism base on lock keyword.

public sealed class RepositoryFactory
{
   private static RepositoryFactory _instance;
   private static readonly object _padlock = new object();

   public static RepositoryFactory Instance
   {
      get
      {
         lock (_padlock)
         {
            return _instance ?? (_instance = new RepositoryFactory());
         }
      }
   }

   private RepositoryFactory()
   {
   }

   public IRepository<T> GetRepositoryInstance<T, TRepository>()
      where TRepository : IRepository<T>, new() where T : System.Data.Objects.DataClasses.EntityObject
   {
      return new TRepository();
   }
}

Conclusion.

This post presents usage an implementation of next, two popular Design Patterns – the Factory Pattern used for creation of objects from same family ( e.g. implementing same Interface) and Singleton Pattern which ensures that there will be only one object of given class in a application  -the presented solution is also thread-safe what is very important in case of growing popularity of parallel programming methods.

Entity Framework + Repository + Unit of Work

Introduction

The topic of this post is presentation an implementation of two quite popular data access patterns – Repository and Unit of Work – in Entity Framework.

Problem definition

Repository mediates between the domain and data mapping layers, acting like an in-memory domain object collection. 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.

Unit of Work maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems. Since EF contains several features of the UoW “out of the box” in this context we use UoW pattern when we need some additional behaviours ( mostly connected with concurrency checking) not provided by EF.

Solution

Firstly let’s define the interface representing Unit of Work pattern:

interface IUnitOfWork
{
    void Commit();
    void Rollback();
}

Next is an concrete class implementing this interface. We can notice that main work is done by ObjectContext class.

class UnitOfWork : IUnitOfWork, IDisposable
{
   private readonly ObjectContext _context;

   public UnitOfWork(ObjectContext context)
   {
      _context = context;
   }

   public void Commit()
   {
      //Some additional operations
      // ...
      _context.SaveChanges();
   }

   public void Rollback()
   {
      //Some additional operations
      // ...
      _context.Refresh(RefreshMode.StoreWins, object);
   }

   public void Dispose()
   {
      _context.Dispose();
   }
}

When Unit of Work is created we can start implementing Repository pattern. As in previous example we  start with an interface for this pattern.

interface IRepository<T> where T : class
{
   IEnumerable<T> GetAll();
   IEnumerable<T> GetByQuery(Expression<Func<T, bool>> where);
   void Delete(T entity);
   void Add(T entity);
}

Than the abstract repository class is created. While in UoW implementation main part of job is done by ObjectContex class, here the ObjectSet<T> is most useful.

abstract class AbstractRepository<T> : IRepository<T> where T : class
{
   private readonly IObjectSet<T> _objects;

   public AbstractRepository(ObjectContext context)
   {
      _objects = context.CreateObjectSet<T>();
   }

   public IEnumerable<T> GetAll()
   {
      return _objects.ToList();
   }

   public IEnumerable<T> GetByQuery(Expression<Func<T, bool>> where)
   {
      return _objects.Where(where);
   }

   abstract public T GetByID(int ID);

   public void Delete(T entity)
   {
      _objects.DeleteObject(entity);
   }

   public void Add(T entity)
   {
      _objects.AddObject(entity);
   }
}

The last step is creating a repository class for each our entity class. Below I present an example of such concrete repository.

class BookRepository : AbstractRepository<Books>
{
   public BookRepository(ObjectContext context)
      : base(context)
   {
   }

   public override Books GetByID(int ID)
   {
      return _objects.First(n => n.ID == ID);
   }
}

Eaxmple code

using (PracaEntities context = new PracaEntities())
{
   IUnitOfWork unitOfWork = new UnitOfWork(context);
   BookRepository bookRepo = new BookRepository(context);
   bookRepo.Add(new Books());
   unitOfWork.Commit();
}

Conclusion
This post presents usage of two very popular patterns – Repository and Unit of Work – in Entity Framework. Presented implementation gives us a possibility of encapsulation ObjectContext class in UnitOfWork class. We also have possibility of developing this class with more features and behaviours such as concurrency checking during save operations. The second part of post presented the implementation of repository pattern. The presented solution is generic and very easy for future development. Repository pattern provides developers a easy data access façade for each object set and defines most popular operations done on data sets.

Entity Framework: many-to-many relationships

Introduction

Before I start with design patterns and all information about them I have to give You some information about one feature of Entity Framework which will be very useful in our future reflections. The topic of this post is many-to-many relationship handling in Entity Framework.

Problem definition

A many-to-many relationship is a type of cardinality that refers to the relationship between two entities A and B in which A may contain a parent row for which there are many children in B and vice versa. For instance, think of A as Authors, and B as Books. An Author can write several Books, and a Book can be written by several Authors. Because most database management systems only support one-to-many relationships, it is necessary to implement such relationships physically via a third junction table, say, AB with two one-to-many relationships A -> AB and B -> AB. In this case the logical primary key for AB is formed from the two foreign keys. Thus, assuming that EF tries to map all tables on the classes directly we should get another, additional class which is created for the junction table and it contains only two navigational properties ( so called Associative Entity).

Solution

Entity framework handles tables participating in many-to-many relationship in a nice way. If the junction table only consists of the foreign keys and no other columns, then that table is omitted by EF and the two sides get a navigational property exposing a collection of the other side. If the junction table contains other fields as well (e.g. the table has its own primary key column), then that junction table is included in the model with many-to-one relationships with both the participating tables.

Please consider following example presenting many-to-many relationship  between Books and Authors

Figure 1: SQL Schema

The generated Entity Model will look something like:

Figure 2: Entity model

Thanks to such a way of mapping objects by Entity Framework we can easily manipulate and query data. Bellow I will present several examples of querying against this data.

Example Code

Finding an authors collection for book of given title.

Books searchedBook = context.Books.First(n => n.BookDescriptions.Title == searchedTitle);
IEnumerable<Authors> authorsCollection = searchedBook.BookDescriptions.Authors;

Finding a titles collection for given author

Authors searchedAuthor = context.Authors.First(n => n.Surname == searchedSurname);
IEnumerable<string> titleCollection = searchedAuthor.BookDescriptions.Select(n => n.Title);

Finding a book list for given author

Authors searchedAuthor = context.Authors.First(n => n.Surname == searchedSurname);
IEnumerable<Books> bookList = searchedAuthor.BookDescriptions.Select(n => n.Books.First());

Limitations

Unfortunately ( or maybe fortunately) EF behaves in above present way only in case of junction tables which contains only two foreign keys. But, of course, it is not a drawback – if You had had to insert additional columns into junction table it represents not only simple association between two entities but rather an association class.

Conclusion

I hope You like this short introduction to handling many-to-many relationships in Entity Framework 4.0. In the beginning I’ve defined a problem which could have happened during using O/R mapping and than I’ve explained how EF handles such a situation. Next, some example source code has been presented. At the end I also have presented some limitations of EF in this area.

Follow

Get every new post delivered to your Inbox.