Vlad's blog

In programming veritas

Posts Tagged ‘Entity Framework

Task Manager: data access layer

leave a comment »

This is the third post of a series of posts on developing Web applications using ASP.Net MVC. The previous two posts are available here:

The source code is available on CodePlex.

The data access layer allows application components to abstract from implementation details of a specific database access technology. Since we use ORM, we already have a substantial level of abstraction that is implemented in the ORM, in our case, Entity Framework. In the case of a simple application like Task Manager, perhaps, there is no need for a separate level of abstraction to isolate parts of the EF from other system components. The only advantage here is that we can easily migrate to another ORM, such as NHibernate. On the other hand, it does not require much effort and demonstrates the good approach in terms of application architecture.
In this case, the standard solution is to use a pattern Repository in conjunction with Unit of work .
From a design standpoint it is important to decide which entity requires a separate repository, and what is not. Eric Evans in his book about DDD recommends creating a repository for each aggregate root. In our case we have three aggregate roots: Project, Task, User, respectively, we have three repositories:

  • IProjectRepository
  • ITaskRepository
  • IUserRepository

Since all the repositories have a standard set of CRUD operations, plus methods for searching and filtering, we can define the common interface they must implement.

public interface IRepository<TEntity, TKey>
    where TEntity: IEntity<TKey>
{
    IQueryable<TEntity> All { get; }
    IQueryable<TEntity> AllIncluding(params Expression<Func<TEntity, object>>[] includeProperties);
    TEntity Find(TKey id);
    void Insert(TEntity entity);
    void Update(TEntity entity);
    void Delete(TKey id);
}

All methods should be obvious, except, perhaps, AllIncluding, but I will tell about it later.
Generic interface IRepository has two parameters: TEntity – that defines the serialized class and TKey – type of the primary key (usually int). TEntity must implement the interface IEntity, which defines the Id property to store the primary key values.

public interface IEntity<T>
{
    T Id { get; set; }
}

Pattern Unit of work is implemented using the interface IUnitOfWork, which is available to clients along with a specific repository.

public interface IUnitOfWork
{
    void Save();
}

Read the rest of this entry »

Advertisements

Written by vsukhachev

January 3, 2012 at 7:01 pm

Posted in Development

Tagged with ,