使用异步方法时 EF IdentityDbContext 出现问题

Issue with EF IdentityDbContext when using async Methods

为什么下面的代码总是产生 "An asynchronous module or handler completed while an asynchronous operation was still pending"?

当我使用 'Dim OriginalUser As ApplicationUser = db.Users.Where(Function(p) p.Id = id).ToList(0)' 时它工作正常。

在继承自 IdentityDbContext 的 ApplicationDBContext 上禁用延迟加载。为什么 SaveChanges-Part 的上下文不再可用?我错过了什么?

    Public Async Sub PatchUser(id As String, <FromBody> ChangedUserAttributes As Delta(Of ApplicationUser))
    Using ctx As New ApplicationDbContext
        Validate(ChangedUserAttributes.GetEntity())

        If Not ModelState.IsValid Then
            Throw New HttpResponseException(New HttpResponseMessage(HttpStatusCode.BadRequest))
        End If

        Dim OriginalUser As ApplicationUser = Await ctx.Users.SingleOrDefaultAsync(Function(p) p.Id = id)
        If OriginalUser Is Nothing Then
            Throw New HttpResponseException(HttpStatusCode.NotFound)
        End If

        Try
            ChangedUserAttributes.TrySetPropertyValue("Email", "Emil") 
            ChangedUserAttributes.Patch(OriginalUser)
            Await ctx.SaveChangesAsync
            Return
        Catch ex As Exception
            Throw New HttpResponseException(New HttpResponseMessage(HttpStatusCode.BadRequest))
        End Try
    End Using
End Sub

因为Async Sub。这个方法应该是一个返回 Task 的异步函数,并且(如果你自己调用它)它需要用 Await.

来调用

您可以在 async on ASP.NET helpful 上找到我的文章:

When an asynchronous handler completes the request, but ASP.NET detects asynchronous work that hasn’t completed, you get an Invalid­OperationException with the message, “An asynchronous module or handler completed while an asynchronous operation was still pending.” This is usually due to asynchronous code calling an async void method

以及我在 async best practices 上的文章:

Avoid async void... Async methods returning void don’t provide an easy way to notify the calling code that they’ve completed. It’s easy to start several async void methods, but it’s not easy to determine when they’ve finished.