【问题标题】:Repository pattern to execute a stored procedure using Entity Framework使用实体框架执行存储过程的存储库模式
【发布时间】:2013-08-13 05:55:07
【问题描述】:

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

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

【问题讨论】:

    标签: entity-framework repository-pattern


    【解决方案1】:

    向您的通用存储库添加

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

    【讨论】:

    • 如何将 ProductRepository 添加到 _unitOfWork 中能否添加一个 _unitOfWork 类的示例代码,它是如何在那里实现 ProductRepository 的?
    • 无法通过数据库找到 SqlQuery ?
    【解决方案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 );
    

    【讨论】:

      【解决方案3】:

      这个链接引导了我。 [Link]

      但是当您执行存储过程时,您必须将 SP 名称的“exec”告知 例如:如果 sp 是 "sp_aa"

      字符串应该是“exec sp_aa”

      【讨论】:

        猜你喜欢
        • 2013-10-31
        • 2016-09-02
        • 1970-01-01
        • 1970-01-01
        • 2016-12-28
        • 2015-06-05
        • 1970-01-01
        • 1970-01-01
        • 2010-12-11
        相关资源
        最近更新 更多