5

I'm trying to use repository pattern for my vsto project.

How do I use a repository pattern to execute a stored procedure? I'm using Entity Framework. Any link for code sample would really useful

0

3 Answers 3

6

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 } 
      );
2
  • 1
    How do you add ProductRepository to _unitOfWork can you please add a sample code of _unitOfWork class how it implementa ProductRepository there?
    – HaBo
    Jan 4, 2015 at 2:09
  • Cannot find SqlQuery over Database ? Jul 11, 2020 at 7:04
4

A non generic solution in your repository would be:

private int ExecWithStoreProcedure(string query, params object[] parameters)
{
   return _context.Database.ExecuteSqlCommand("EXEC " +  query, parameters);
}

And then a few typical examples of use:

var param = new SqlParameter("SomethingToCheck", SqlDbType.NVarChar) { Value = shortCode };            
var result = ExecWithStoreProcedure("mySchema.myStoredProc @SomethingToCheck", param);

with multiple parameters:

var param1 = new SqlParameter("SomeCode", SqlDbType.VarChar) { Value = shortCode };
var param2 = new SqlParameter("User", SqlDbType.VarChar) { Value = userName };
var result = ExecWithStoreProcedure("mySchema.myStoredProc @SomeCode, @User",  param1, param2 );
1

this link guided me. [Link]

But when you execute stored procedure you have to put "exec" informant of SP name Eg: if sp is "sp_aa"

string should be "exec sp_aa"

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.