Repositories in the data access layer

From this preceding code for the business layer project, we can see that we access the data source via the repository pattern. This enterprise application pattern has been already briefed upon in the previous chapter. Our repositories are present in the data access layer. Although we have a data access layer with repositories present in almost every service for each department, let's just take a look at one of the repositories, which is for the HR department:

    /// <summary> 
/// This repository class takes care of
disposing underlying dbcon/context objects
/// </summary>
public interface IRepository
{
TEntity GetEntity<TEntity>(int id) where TEntity : class;
IEnumerable<TEntity> GetAll<TEntity>() where TEntity : class;
void Create<TEntity>(TEntity entity) where TEntity : class;
void Update<TEntity>(TEntity entity) where TEntity : class;
void Delete<TEntity>(TEntity entity) where TEntity : class;
int GetRecordsCount<TEntity>() where TEntity : class;
}

Now, let's look at the implementation of a generic repository; we have removed some of the trivial code:

    /// <summary> 
/// Generic implementation of IRepository
interface for HR business apps.
/// The class takes will take care of disposing
underlying dbcon/context objects.
/// </summary>
public class GenericRepository : IRepository
{
protected IDataContextCreator _dataContextCreator;
public GenericRepository(IDataContextCreator dataContextCreator)
{
_dataContextCreator = dataContextCreator;
}

public void Create<TEntity>(TEntity entity)
where TEntity : class
{
using (var context = _dataContextCreator.GetDataContext())
{
context.Set<TEntity>().Add(entity);
context.SaveChanges();
}
}

public IEnumerable<TEntity> GetAll<TEntity>()
where TEntity : class
{
using (var context = _dataContextCreator.GetDataContext())
return context.Set<TEntity>().ToList();
}

public int GetRecordsCount<TEntity>() where TEntity : class
{
using (var context = _dataContextCreator.GetDataContext())
return context.Set<TEntity>().Count();
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.19.243