我正在尝试将存储库模式用于我的vsto项目。
如何使用存储库模式执行存储过程?我正在使用实体框架。代码示例的任何链接都非常有用
答案 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)