How can I use a stored procedure + repository + unit of work patterns in Entity Framework?

sara Sodagari picture sara Sodagari · Jul 28, 2013 · Viewed 28.6k times · Source

I have MVC web application project with Entity Framework code first. In this project I am going to use generic repository and unit of work patterns. Plus I want to use stored procedures for get list by and get-list methods.

How can I use stored procedures with generic repository and unit of work patterns?

Answer

sunil picture sunil · Aug 1, 2013

To your generic repository add

public IEnumerable<T> ExecWithStoreProcedure(string query, params object[] parameters)
{
        return _context.Database.SqlQuery<T>(query, parameters);
}

And then you can call it with any unitofwork/repository like

IEnumerable<Products> products = 
             _unitOfWork.ProductRepository.ExecWithStoreProcedure(
             "spGetProducts @bigCategoryId",
             new SqlParameter("bigCategoryId", SqlDbType.BigInt) { Value = categoryId } 
      );