Implementing Repository Pattern with Entity Framework – Code First Model Approach

When working with Entity Framework – Code First model approach, developer creates POCO entities for Database tables. The benefit of using Code First model is to have POCO entity for each table that can be used as either WCF Data Contracts or you can apply your own custom attributes to handle Security, Logging, etc. and there is no mapping needed as we used to do in Entity Framework (Model First) approach if the application architecture is n-tier based.

Considering the Data Access layer, we will implement a repository pattern that encapsulates the persistence logic in a separate class. This class will be responsible to perform database operations. Let’s suppose the application is based on n-tier architecture and having 3 tiers namely Presentation, Business and Data Access. Common library contains all our POCO entities that will be used by all the layers.

Presentation Layer: Contains Views, Forms

Business Layer: Managers that handle logic functionality

Data Access Layer: Contains Repository class that handles CRUD operations

Common Library: Contain POCO entities.

We will implement an interface named “IRepository” that defines the signature of all the appropriate generic methods needed to perform CRUD operation and then implement the Repository class that defines the actual implementation of each method. We can also instantiate Repository object using Dependency Injection or apply Factory pattern.

Code Snippet: IRepository


public
interface
IRepository : IDisposable

{


///
<summary>


/// Gets all objects from database


///
</summary>


///
<returns></returns>


IQueryable<T> All<T>() where T : class;


///
<summary>


/// Gets objects from database by filter.


///
</summary>


///
<param name=”predicate”>Specified a filter</param>


///
<returns></returns>


IQueryable<T> Filter<T>(Expression<Func<T, bool>> predicate) where T : class;


///
<summary>


/// Gets objects from database with filting and paging.


///
</summary>


///
<typeparam name=”Key”>


///
<param name=”filter”>Specified a filter</param>


///
<param name=”total”>Returns the total records count of the filter.</param>


///
<param name=”index”>Specified the page index.</param>


///
<param name=”size”>Specified the page size</param>


///
<returns></returns>


IQueryable<T> Filter<T>(Expression<Func<T, bool>> filter, out
int total, int index = 0, int size = 50) where T : class;


///
<summary>


/// Gets the object(s) is exists in database by specified filter.


///
</summary>


///
<param name=”predicate”>Specified the filter expression</param>


///
<returns></returns>


bool Contains<T>(Expression<Func<T, bool>> predicate) where T : class;


///
<summary>


/// Find object by keys.


///
</summary>


///
<param name=”keys”>Specified the search keys.</param>


///
<returns></returns>

T Find<T>(params
object[] keys) where T : class;


///
<summary>


/// Find object by specified expression.


///
</summary>


///
<param name=”predicate”></param>


///
<returns></returns>

T Find<T>(Expression<Func<T, bool>> predicate) where T : class;


///
<summary>


/// Create a new object to database.


///
</summary>


///
<param name=”t”>Specified a new object to create.</param>


///
<returns></returns>

T Create<T>(T t) where T : class;


///
<summary>


/// Delete the object from database.


///
</summary>


///
<param name=”t”>Specified a existing object to delete.</param>


int Delete<T>(T t) where T : class;


///
<summary>


/// Delete objects from database by specified filter expression.


///
</summary>


///
<param name=”predicate”></param>


///
<returns></returns>


int Delete<T>(Expression<Func<T, bool>> predicate) where T : class;


///
<summary>


/// Update object changes and save to database.


///
</summary>


///
<param name=”t”>Specified the object to save.</param>


///
<returns></returns>


int Update<T>(T t) where T : class;


///
<summary>


/// Select Single Item by specified expression.


///
</summary>


///
<typeparam name=”T”></typeparam>


///
<param name=”expression”></param>


///
<returns></returns>

T Single<T>(Expression<Func<T, bool>> expression) where T : class;


void SaveChanges();


void ExecuteProcedure(String procedureCommand, params
SqlParameter[] sqlParams);

}

Code Snippet: Repository

public
class
Repository : IRepository

{


DbContext Context;


public Repository()

{

Context = new
DBContext();

}


public Repository(DBContext context)

{

Context = context;

}


public
void CommitChanges()

{

 Context.SaveChanges();

}


public T Single<T>(Expression<Func<T, bool>> expression) where T : class

{


return All().FirstOrDefault(expression);

}


public
IQueryable<T> All<T>() where T : class

{


return Context.Set().AsQueryable();

}


public
virtual
IQueryable<T> Filter<T>(Expression<Func<T, bool>> predicate) where T : class

{


return Context.Set<T>().Where<T>(predicate).AsQueryable<T>();

}


public
virtual
IQueryable<T> Filter<T>(Expression<Func<T, bool>> filter, out
int total, int index = 0, int size = 50) where T : class

{


int skipCount = index * size;


var _resetSet = filter != null ? Context.Set().Where(filter).AsQueryable() : Context.Set().AsQueryable();

 _resetSet = skipCount == 0 ? _resetSet.Take(size) : _resetSet.Skip(skipCount).Take(size);

total = _resetSet.Count();


return _resetSet.AsQueryable();

}


public
virtual T Create(T TObject) where T : class

{


var newEntry = Context.Set().Add(TObject);

Context.SaveChanges();


return newEntry;

}


public
virtual
int Delete(T TObject) where T : class

{

 Context.Set().Remove(TObject);


return Context.SaveChanges();

}


public
virtual
int Update(T TObject) where T : class

{


try

{


var entry = Context.Entry(TObject);

 Context.Set().Attach(TObject);

entry.State = EntityState.Modified;


return Context.SaveChanges();

}


catch (OptimisticConcurrencyException ex)

{


throw ex;

}

}


public
virtual
int Delete<T>(Expression<Func<T, bool>> predicate) where T : class

{


var objects = Filter<T>(predicate);


foreach (var obj in objects)

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


return Context.SaveChanges();

}


public
bool Contains<T>(Expression<Func<T, bool>> predicate) where T : class

{


return Context.Set<T>().Count<T>(predicate) > 0;

}


public
virtual T Find<T>(params
object[] keys) where T : class

{


return (T)Context.Set<T>().Find(keys);

}


public
virtual T Find<T>(Expression<Func<T, bool>> predicate) where T : class

{


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

}


public
virtual
void ExecuteProcedure(String procedureCommand, params
SqlParameter[] sqlParams){

 Context.Database.ExecuteSqlCommand(procedureCommand, sqlParams);

}


public
virtual
void SaveChanges()

{

Context.SaveChanges();

}


public
void Dispose()

{


if (Context != null)

Context.Dispose();

}

}

The benefit of using Repository pattern is that all the database operations will be managed centrally and in future if you want to change the underlying database connector you can add another Repository class and defines its own implementation or change the existing one.

4 thoughts on “Implementing Repository Pattern with Entity Framework – Code First Model Approach

  1. Hi Ovais,

    Thanks. Nice post. Helped me a lot. However I am struggling in implementing paging. I am herewith posting my code. See if you can help me. Thanks in advance.

    Paging Interface

    public interface IPagination : IList
    {
    int PageIndex { get; }
    int PageSize { get; }
    int TotalCount { get; }
    int TotalPages { get; }
    bool HasPreviousPage { get; }
    bool HasNextPage { get; }
    }

    Paging Class

    public Pagination(IQueryable source, int pageIndex, int pageSize)
    {
    int totalRecords = source.Count();
    this.TotalCount = totalRecords;
    this.PageIndex = pageIndex;
    this.PageSize = pageSize;
    this.TotalPages = totalRecords / pageSize;
    if (totalRecords % pageSize > 0)
    TotalPages++;
    this.AddRange(source.Skip(PageIndex * pageSize).Take(pageSize).ToList());
    }

    public Pagination(List source, int pageIndex, int pageSize)
    {
    int totalRecords = source.Count();
    this.TotalCount = totalRecords;
    this.PageIndex = pageIndex;
    this.PageSize = pageSize;
    this.TotalPages = totalRecords / pageSize;
    if (totalRecords % pageSize > 0)
    TotalPages++;
    this.AddRange(source.Skip(PageIndex * pageSize).Take(pageSize).ToList());
    }

    public int PageIndex { get; private set; }
    public int PageSize { get; private set; }
    public int TotalCount { get; private set; }
    public int TotalPages { get; private set; }

    public bool HasPreviousPage
    {
    get { return (PageIndex > 0); }
    }

    public bool HasNextPage
    {
    get { return (PageIndex + 1 < TotalPages); }
    }

    Generic Repository Interface

    public interface IRepository where T : class
    {
    void Add(T entity);
    void Delete(T entity);
    void Update(T entity);
    IQueryable GetAll();
    T FindBy(Expression<Func> expression);
    IQueryable FilterBy(Expression<Func> expression);
    IPagination GetPaged(Expression<Func> expression,int pageIndex, int pageSize);
    }

    Repository Base

    public abstract class Repository : IRepository where T : class
    {
    private STNDataContext _stnDataContext;
    private readonly IDbSet _dbSet;

    protected Repository(IDatabaseFactory databaseFactory)
    {
    DatabaseFactory = databaseFactory;
    _dbSet = StnDataContext.Set();
    }

    protected IDatabaseFactory DatabaseFactory { get; private set; }
    public STNDataContext StnDataContext
    {
    get { return _stnDataContext ?? (_stnDataContext = new STNDataContext()); }
    }
    public void Add(T entity)
    {
    _dbSet.Add(entity);
    //_stnDataContext.Commit();
    }

    public void Delete(T entity)
    {
    _dbSet.Remove(entity);
    }

    public void Update(T entity)
    {
    _dbSet.Attach(entity);
    _stnDataContext.Entry(entity).State = EntityState.Modified;
    //_stnDataContext.Commit();
    }

    public IQueryable GetAll()
    {
    return _dbSet.ToList().AsQueryable();
    }

    public T FindBy(Expression<Func> expression)
    {
    return FilterBy(expression).FirstOrDefault();
    }

    public IQueryable FilterBy(Expression<Func> expression)
    {
    return GetAll().Where(expression).AsQueryable();
    }

    public IPagination GetPaged(Expression<Func> expression,int pageIndex, int pageSize)
    {
    //return FilterBy(expression).AsQueryable().Skip(pageIndex*pageSize).Take(pageSize).ToList();
    throw new NotImplementedException();
    }
    }

    Can you help me figure out how my GetPaged() method should be? Please comment with your suggestions.

    Thanks

  2. Hello Ovais, I’ve implemented the Repository pattern as it is in my project, however when I try to add a new item in the database I get an error that says “The entity type Object is not part of the model for the current context” what could I be doing wrong?

  3. I’ve been exploring for a little for any high-quality articles
    or weblog posts in this kind of house . Exploring in Yahoo
    I eventually stumbled upon this site. Studying this info So i
    am glad to convey that I have an incredibly good uncanny feeling I
    found out just what I needed. I such a lot surely will make
    sure to do not disregard this website and provides it a look regularly.

Leave a comment