Repository pattern reduce the controller code complexity. We
write the most of all business logic in
Repository with the help of entity frameworks classes.
Repository work like a mediator that means its work between
business logic and data access layers.
Steps of Implementing repository pattern in MVC 5
namespace PCX.Core.Repositories
{
/// <typeparam
name="C"></typeparam>
/// <typeparam
name="T"></typeparam>
public abstract class GenericRepository<C, T> :IGenericRepository<T> where T : class where C : DbContext, new()
{
private C _entities = new C();
public C Context
{
get { return _entities; }
set { _entities = value; }
}
public virtual IQueryable<T> GetAll()
{
IQueryable<T> query = _entities.Set<T>();
return query;
}
public IQueryable<T> FindBy(System.Linq.Expressions.Expression<Func<T, bool>> predicate)
{
IQueryable<T> query = _entities.Set<T>().Where(predicate);
return query;
}
public virtual void Add(T entity)
{
_entities.Set<T>().Add(entity);
}
public virtual void Delete(T entity)
{
_entities.Set<T>().Remove(entity);
}
public virtual void Edit(T entity)
{
_entities.Entry(entity).State =
System.Data.Entity.EntityState.Modified;
}
public virtual void Save()
{
_entities.SaveChanges();
}
}
}
namespace PCX.Core.Repositories
{
public interface IGenericRepository<T> where T : class
{
IQueryable<T> GetAll();
IQueryable<T> FindBy(Expression<Func<T, bool>> predicate);
void Add(T entity);
void Delete(T entity);
void Edit(T entity);
void Save();
}
}
namespace PCX.Core.Repositories
{
public interface IEmployeeRepository
{
List<Employee> List(string emailId);
}
}
namespace PCX.Core.Repositories
{
/// <summary>
/// Employee repository class handle all methods related to
Tenant entity.
/// </summary>
public class EmployeeRepository : GenericRepository<PCXEntities, Employee>, IEmployeeRepository
{
/// <summary>
/// Check that employee exists in database or not , If
employee exists in database then return entity.
public List<Employee> List(string emailId)
{
return Context.Employees.Where(em => em.EmailID ==
emailId).ToList();
}
}
}