dotnet / dotnet/efcore

Incorrect "ObjectDisposedException" on accessing DbContext when using async methods

Open
#33,672 3 comments 0 reactions 0 assignees View on GitHub
area-dbcontext customer-reported
Dominant language
C#
Stars
14.8k
Forks
3.4k
PR merge metrics
PR metrics pending

Description

Currently there's an incorrect exception message shown when accessing context generated form async methods. Code attached
[EFMessageIssue.zip](https://github.com/dotnet/efcore/files/15200978/EFMessageIssue.zip)

How I stumbled upon this

1. Generate migration for entities.
2. Remove Keyless attribute. (It got removed by mistake while doing some changes, that's when I encountered this bug)
3. Build & run the application.
4. Access /test/sync endpoint and it will generate error as below

```
The entity type 'PersonAddress' requires a primary key to be defined. If you intended to use a keyless entity type, call 'HasNoKey' in 'OnModelCreating'. For more information on keyless entity types, see https://go.microsoft.com/fwlink/?linkid=2141943.
```

5. Now execute /test/async and it will generate below error

```
Cannot access a disposed context instance. A common cause of this error is disposing a context instance 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 instance, or wrapping it in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.
Object name: 'DataContext'.
```

The initial error message is quite confusing as it took a lot of time to figure out what the exact cause was. Even the synchronous approach was reached by trying to cancel out any missing async/awaits thought it was a straight forward call. This should be improved to give out appropriate message even for async methods like we do for sync methods.

### Include provider and version information

EF Core version: 8.0.4
Database provider: Microsoft.EntityFrameworkCore.SqlServer
Target framework: .NET 8.0
Operating system: Win 11
IDE: Visual Studio 2022 17.9.6

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.