5

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

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

4

3 回答 3

6

到您的通用存储库添加

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

然后您可以使用任何工作单元/存储库来调用它,例如

IEnumerable<Products> products = 
             _unitOfWork.ProductRepository.ExecWithStoreProcedure(
             "spGetProducts @bigCategoryId",
             new SqlParameter("bigCategoryId", SqlDbType.BigInt) { Value = categoryId } 
      );
于 2013-09-25T22:32:53.717 回答
3

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

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 );
于 2015-04-09T11:26:00.423 回答
1

这个链接引导了我。[关联]

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

字符串应该是“exec sp_aa”

于 2013-08-15T11:36:30.747 回答