无法访问已处置的对象.此错误的一个常见原因是处理上下文 [英] Cannot access a disposed object. A common cause of this error is disposing a context

查看:26
本文介绍了无法访问已处置的对象.此错误的一个常见原因是处理上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

<块引用>

Microsoft.EntityFrameworkCore.Query[10100]

迭代上下文类型app.Models.ApplicationDbContext"的查询结果时发生异常.

System.ObjectDisposedException:无法访问已处理的对象.此错误的一个常见原因是处理从依赖注入解析的上下文,然后尝试在应用程序的其他地方使用相同的上下文实例.如果您在上下文上调用 Dispose() 或将上下文包装在 using 语句中,则可能会发生这种情况.如果你使用依赖注入,你应该让依赖注入容器来处理上下文实例.

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

这是我的 Edit.cshtml 内容:

@page@model 编辑模型@{ViewData["Title"] = "编辑书籍";}<h2>编辑书籍</h2><div class="row justify-content-center"><div class="col-md-6"><form method="post" class="form-b​​order"><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 class="form-group"><label asp-for="Book.Description"></label><input asp-for="Book.Description" class="form-control"/>

<div class="form-group"><label asp-for="Book.Author"></label><input asp-for="Book.Author" class="form-control"/>

<input asp-for="Book.Id" type="hidden"><button type="submit" class="btn btn-primary">更新</button><a asp-page="Index" class="btn btn-success">返回列表</a></表单>

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

public async void OnGet(int id){Book = await _db.Books.SingleOrDefaultAsync(x => x.Id == id);如果(书 == 空){RedirectToPage("索引");}}

我使用的是 .Net Core 2.2.104

此外,当我运行命令 dotnet ef --version 时,它会生成 Entity Framework Core .NET 命令行工具2.2.2-service-10034

解决方案

这是因为您的方法返回类型 async void.通常,当您在代码中使用 async void 时,这是个坏消息,因为:

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

公共异步任务 OnGet(int id){Book = await _db.Books.SingleOrDefaultAsync(x => x.Id == id);如果(书 == 空){RedirectToPage("索引");}}

更多详情:

I have written a simple application and when I navigate to my edit page the below error pops up.

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.

It seems EF is proving a useful information which I can not understand. The tricky part of this error is that it happens randomly when I navigate to the edit page. Sometime it works, Sometimes it fails to load some properties on Edit.cshtml but still works and sometimes the application crashes with provided error just in my console. Another strange happen is that it dose not generate any 500 or 5xx error. It just simply crashes and stop the application.

Here is my Edit.cshtml content:

@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>

Here is My Edit.cshtm.cs OnGet method:

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

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

I am using .Net Core 2.2.104

Also when I run command dotnet ef --version it generates Entity Framework Core .NET Command-line Tools 2.2.2-servicing-10034

解决方案

This is because of your method return type async void. In general, when you are using async void in your code it’s bad news, because:

So return async Task instead of async void from your method as follows:

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

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

For more details:

这篇关于无法访问已处置的对象.此错误的一个常见原因是处理上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
C#/.NET最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆