使用Entity Framework执行存储过程的存储库模式

时间:2013-08-13 05:55:08

标签: entity-framework repository-pattern

我正在尝试将存储库模式用于我的vsto项目。

如何使用存储库模式执行存储过程?我正在使用实体框架。代码示例的任何链接都非常有用

3 个答案:

答案 0 :(得分:6)

到您的通用存储库添加

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

然后您可以使用任何unitofwork / repository(如

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

答案 1 :(得分:2)

您的存储库中的非通用解决方案是:

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

然后是几个典型的使用示例:

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

有多个参数:

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 );

答案 2 :(得分:1)

此链接指导了我。 [Link]

但是当你执行存储过程时,你必须输入SP名称的“exec”线人 例如:如果sp是“sp_aa”

字符串应为“exec sp_aa”