.net - 无法访问已处置的对象。导致此错误的一个常见原因是处置上下文

标签 .net entity-framework .net-core entity-framework-core

我编写了一个简单的应用程序,当我导航到编辑页面时,会弹出以下错误。

Microsoft.EntityFrameworkCore.Query[10100]

An exception occurred while iterating over the results of a query for context type 'app.Models.ApplicationDbContext'.

System.ObjectDisposedException: Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.

EF 似乎提供了一些我无法理解的有用信息。这个错误的棘手部分是当我导航到编辑页面时它会随机发生。有时它可以工作,有时它无法在 Edit.cshtml 上加载某些属性,但仍然可以工作,有时应用程序会因我的控制台中提供的错误而崩溃。另一个奇怪的情况是它不会生成任何 5005xx 错误。它只是简单地崩溃并停止应用程序。

这是我的Edit.cshtml内容:

@page
@model EditModel
@{
    ViewData["Title"] = "Edit Book";
}

<h2>Edit Book</h2>

<div class="row justify-content-center">
    <div class="col-md-6">
        <form method="post" class="form-border">
            <div asp-validation-summary="All" class="validation-container alert alert-danger"></div>
            <div class="form-group">
                <label asp-for="Book.Name"></label>
                <input asp-for="Book.Name" class="form-control" />
                <span class="form-text text-danger" asp-validation-for="Book.Name"></span>
            </div>
            <div class="form-group">
                <label asp-for="Book.Description"></label>
                <input asp-for="Book.Description" class="form-control" />
            </div>
            <div class="form-group">
                <label asp-for="Book.Author"></label>
                <input asp-for="Book.Author" class="form-control" />
            </div>
            <input asp-for="Book.Id" type="hidden">
            <button type="submit" class="btn btn-primary">Update</button>
            <a asp-page="Index" class="btn btn-success">Back To List</a>
        </form>
    </div>
</div>

这是我的 Edit.cshtm.cs OnGet 方法:

public async void OnGet(int id)
{
    Book = await _db.Books.SingleOrDefaultAsync(x => x.Id == id);

    if(Book == null)
    {
        RedirectToPage("Index");
    }
}

我正在使用.Net Core 2.2.104

此外,当我运行命令 dotnet ef --version 时,它会生成 Entity Framework Core .NET Command-line Tools 2.2.2-servicing-10034

最佳答案

这是因为您的方法返回类型async void。一般来说,当您在代码中使用 async void 时,这是个坏消息,因为:

  • 您迫不及待地等待它的完成
  • 任何未处理的异常都会终止您的进程(哎呀!)

因此,从您的方法中返回 async Task 而不是 async void,如下所示:

public async Task OnGet(int id)
{
    Book = await _db.Books.SingleOrDefaultAsync(x => x.Id == id);

    if(Book == null)
    {
       RedirectToPage("Index");
    }
}

了解更多详情:

关于.net - 无法访问已处置的对象。导致此错误的一个常见原因是处置上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55543595/

相关文章:

c# - 'Microsoft.Jet.OLEDB.4.0' 提供者未在本地机器上注册

c# - 在选项卡之间切换时,如何将焦点恢复到之前聚焦的 TabPage 控制

c# - SDN Entity Framework 控制台演示无法编译

c# - 具有泛型和 `InternalsVisibleTo` 的内部构造函数

c# - 歧义操作异常 : Multiple actions matched in MVC Core

c# - ASP.NET Core CRUD 工具 : command not found but actually installed

.net - 基于多个属性启用/禁用菜单项的最佳方法

.net - WPF TreeView 绑定(bind)

c# - 实体或复杂类型...无法在 LINQ to Entities 查询中构造

c# - 如何使用 Entity Framework 访问子表