Pages

Friday, 6 January 2017

Create a Repository pattern and Unit of Work for Entity Framework in ASP.NET MVC

In this post we are going to see how to create a Repository Pattern and UnitOfWork for Entity Framework.

Repository Pattern is the pattern where common logic for different entities resides in one place, then we have to derive that common logic for each repository. Here we take a example of Employee, Department and Task Models for entity framework using this we will create a Repository pattern. Let we see one by one.

Now we have to create a Generic Repository for the Context, Then we have to derive it for all respository. The Generic Repository will contain common operation like Get, GetAll, Fetch, Insert, InsertCollection, Update, Delete, DeleteCollection, SingleOrDefault, FirstOrDefault

publicinterfaceIRepository<T>

{

T Get(int id);

IEnumerable<T>
GetAll();

IEnumerable<T>
Fetch(Expression<Func<T, bool>>
predicate);

void Insert(T obj);

void InsertCollection(IEnumerable<T>
collection);

T update(T obj);

void Delete(T obj);

void DeleteCollection(IEnumerable<T>
collection);

T SingleOrDefault(Expression<Func<T, bool>> predicate);

T FirstOrDefault(Expression<Func<T, bool>> predicate);

}

publicclassRepository<T> : IRepository<T> whereT : class

{

protectedDbContext context;

public Repository(DbContext context)

{

this.context = context;

}

publicvoid Delete(T obj)

{

context.Set<T>().Remove(obj);

}

publicvoid
DeleteCollection(IEnumerable<T>
collection)

{

context.Set<T>().RemoveRange(collection);

}

publicIEnumerable<T>
Fetch(Expression<Func<T, bool>>
predicate)

{

return context.Set<T>().Where(predicate);

}

publicT
FirstOrDefault(Expression<Func<T, bool>> predicate)

{

return context.Set<T>().FirstOrDefault(predicate);

}

publicT Get(int id)

{

return context.Set<T>().Find(id);

}

publicIEnumerable<T>
GetAll()

{

return context.Set<T>().ToList();

}

publicvoid Insert(T obj)

{

context.Set<T>().Add(obj);

}

publicvoid
InsertCollection(IEnumerable<T>
collection)

{

context.Set<T>().AddRange(collection);

}

publicT
SingleOrDefault(Expression<Func<T, bool>> predicate)

{

return context.Set<T>().SingleOrDefault(predicate);

}

publicT update(T obj)

{

context.Entry<T>(obj).State = EntityState.Modified;

return obj;

}

}

Now we are going to create Repository for all Entities.

publicinterfaceIEmployeeRepository : IRepository<Employee>

{

IEnumerable<Task>
GetTasks(int EmployeeId);

}

publicinterfaceIDepartmentRepository : IRepository<Department>

{

IEnumerable<Employee> GetEmployees(int departmentid);

}

publicinterfaceITaskRepository : IRepository<Task>

{

Employee GetEmployee(int taskid);

}

In each Repository we are adding individual methods which are needed for that repositories.