【问题标题】:How to call Stored Procedure asynchronously?如何异步调用存储过程?
【发布时间】:2017-06-29 06:23:54
【问题描述】:

在我的 ASP.NET MVC (C#) 应用程序中,我使用 Entity Framework 并像这样调用存储过程:

    public virtual ObjectResult<ART_USP_GetAssetReportGridList_Result> ART_USP_GetAssetReportGridList(string searchExpression, string sortExpression, string sortDirection, Nullable<int> startIndex, Nullable<int> pageSize, ObjectParameter count)
    {
        var searchExpressionParameter = searchExpression != null ?
            new ObjectParameter("SearchExpression", searchExpression) :
            new ObjectParameter("SearchExpression", typeof(string));

        var sortExpressionParameter = sortExpression != null ?
            new ObjectParameter("SortExpression", sortExpression) :
            new ObjectParameter("SortExpression", typeof(string));

        var sortDirectionParameter = sortDirection != null ?
            new ObjectParameter("SortDirection", sortDirection) :
            new ObjectParameter("SortDirection", typeof(string));

        var startIndexParameter = startIndex.HasValue ?
            new ObjectParameter("StartIndex", startIndex) :
            new ObjectParameter("StartIndex", typeof(int));

        var pageSizeParameter = pageSize.HasValue ?
            new ObjectParameter("PageSize", pageSize) :
            new ObjectParameter("PageSize", typeof(int));

        return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<ART_USP_GetAssetReportGridList_Result>("ART_USP_GetAssetReportGridList", searchExpressionParameter, sortExpressionParameter, sortDirectionParameter, startIndexParameter, pageSizeParameter, count);
    }

这里的ART_USP_GetAssetReportGridList是存储过程名称。这是一个同步调用。如果记录数超过 3000,则此调用将给我超时错误。

如何在不出现超时错误的情况下异步进行此调用?

【问题讨论】:

  • 每次 sql 往返不允许超过 100 条记录 (pageSize)。解决的办法不是异步调用sp,而是利用已有的分页机制。
  • 在将记录绑定到网格视图时使用分页机制。但我也使用相同的方法导出到 excel。因为页面大小将是总记录,在这种情况下我不能限制页面大小的调用。

标签: c# asp.net-mvc entity-framework asynchronous


【解决方案1】:

您可以如下增加特定操作的超时时间。

((IObjectContextAdapter)this).ObjectContext.CommandTimeout = 180; // in sec

或者在您的 DbContext 构造函数中设置此代码。

【讨论】:

  • 哇..哇..哇..它的工作就像一个魅力@Houssam Hamdan。非常感谢。
【解决方案2】:

异步调用它不会有任何区别。您收到命令超时错误。为了避免这种情况,您应该增加 SQL 连接的 CommandTimeout 设置。但我非常建议不要这样做,并查看您的存储过程效率 - 30 秒默认超时应该是方式,远远超过您的需要。

【讨论】:

    【解决方案3】:

    请试试这个

     var data = ObjectContext.Database.SqlQuery<ART_USP_GetAssetReportGridList_Result>("ART_USP_GetAssetReportGridList", searchExpressionParameter, sortExpressionParameter, sortDirectionParameter, startIndexParameter, pageSizeParameter, count).FirstOrDefaultAsync();
    

    【讨论】:

    • FirstOrDefaultAsync 将仅返回序列中的第一个元素。根据我的方法的结构,这一行也有一些编译错误。
    猜你喜欢
    • 2010-09-06
    • 1970-01-01
    • 2019-01-22
    • 2019-05-07
    • 1970-01-01
    • 2011-03-18
    • 2020-01-15
    • 2021-04-02
    • 1970-01-01
    相关资源
    最近更新 更多