c# - SELECT COUNT(*) 查询时抛出异常

标签 c#

我正在尝试查询表中的行数,并将其返回到我的 Controller 操作。我正在使用 Dapper 作为我的 Micro-ORM,并且在尝试实现此目标时似乎遇到了一些问题。

服务方式

public Task<int> GetPostCount()
{
    using (var connection = new SqlConnection(configuration.GetConnectionString("DefaultConnection")))
    {
        return connection.QuerySingleAsync<int>(SqlQueries.Post.SelectPostCount);
    }
}

Controller 操作

[HttpGet("Posts/{page:int?}")]
public async Task<IActionResult> Posts(int page)
{
    IEnumerable<PostHighlightViewModel> posts = await this.postService.GetAllPosts(postsPerPage, page < 1 ? 1 : page);
    if (posts.Count() == 0)
    {
        // BOOM goes the dynamite - right here.
        int numberOfPosts = await this.postService.GetPostCount();
        int pageToFetch = numberOfPosts / postsPerPage;
        posts = await this.postService.GetAllPosts(postsPerPage, pageToFetch);
    }

    return View("Index", posts);
}

我正在执行的Sql是

SELECT COUNT(*) FROM POSTS

当我执行查询时,出现以下异常

Application started. Press Ctrl+C to shut down. fail: Microsoft.AspNetCore.Server.Kestrel, Version=1.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60[13] Connection id "0HKSQRDBQRA9E": An unhandled exception was thrown by the application. System.InvalidOperationException: Invalid operation. The connection is closed. at System.Data.SqlClient.SqlCommand.<>c.b__110_0(Task1 result) at System.Threading.Tasks.ContinuationResultTaskFromResultTask2.InnerInvoke() at System.Threading.Tasks.Task.Execute() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Dapper.SqlMapper.d__241.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter1.GetResult() at BlogWeb.Controllers.PostController.d__4.MoveNext() in C:\Users\johnathonsullinger\Source\VSTS\Blog.Core\Source\BlogWeb\Controllers\PostController.cs:line 32 --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.AspNetCore.Mvc.Internal.ObjectMethodExecutor.d__241.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeActionAsync>d__6.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.AspNetCore.Mvc.Internal.FilterActionInvoker.<InvokeActionFilterAsync>d__41.MoveNext() --- End of stack trace from previous location where exception was thrown --- at Microsoft.AspNetCore.Mvc.Internal.FilterActionInvoker.<InvokeAsync>d__32.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.AspNetCore.Mvc.Internal.MvcRouteHandler.<InvokeActionAsync>d__8.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.AspNetCore.Builder.RouterMiddleware.<Invoke>d__4.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.AspNetCore.Hosting.Internal.RequestServicesContainerMiddleware.<Invoke>d__3.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.AspNetCore.Server.Kestrel.Http.Frame1.d__2.MoveNext()

我没有什么可以离开这里来尝试弄清楚发生了什么。我可以毫无问题地进行其他查询,但尝试查询记录计数似乎是一个问题。

我尝试过使用QueryFirstOrDefaultAsyncQuerySingleAsync 。我不应该使用 QueryAsync方法族?

最佳答案

当执行从 using block 返回时,连接将被释放,因此在 async 操作结束之前连接将被关闭。

您可以考虑在 ContinueWith 中关闭连接,以确保它在 async 操作完成时关闭。

或者,我认为您可以在异步调用上使用 await 关键字。

关于c# - SELECT COUNT(*) 查询时抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37977675/

相关文章:

c# - 在可移植 HttpClient 中支持 TLS 1.2 和 1.1

c# - ASP.NET Web 表单删除自动填充的密码字段

c# - 如何在 .Net Core MVC 中为 Azure SignalR 调用 CosmosDBTrigger 和 HttpResponseMessage?

c# - mschart 缩放和滚动

c# - 使用 Visual Studio 2017 的新 csproj 格式如何添加对旧可移植库的支持?

c# - NodaTime 根据国家代码获取国家时间

c# - 为什么我不能引用 System.ComponentModel.DataAnnotations?

c# - 为什么我可以将无效值解析为 .NET 中的枚举?

c# - 最小化窗口时 Bootstrap 文本框宽度和对齐方式发生变化

C#如何知道可移动磁盘是USB驱动器还是SD卡?