Implementing a CancellationToken with EF Core Queries - Strange Behavior When Canceling
I've tried everything I can think of but I've been struggling with this for a few days now and could really use some help. I'm having a hard time understanding I'm working with an unexpected scenario when trying to implement a `CancellationToken` with my Entity Framework Core queries in a .NET 6 application..... Specifically, I expect the queries to terminate gracefully when the token is canceled, but I'm seeing that the operation still runs to completion, resulting in a `DbUpdateConcurrencyException` when the operation is canceled mid-way. Here's a simplified version of the code I'm using: ```csharp public async Task<List<MyEntity>> GetEntitiesAsync(CancellationToken cancellationToken) { using var context = new MyDbContext(); return await context.MyEntities.ToListAsync(cancellationToken); } ``` I call this method from my service layer like this: ```csharp public async Task ProcessDataAsync(CancellationToken cancellationToken) { var entities = await GetEntitiesAsync(cancellationToken); // ... process entities } ``` When I pass a `CancellationToken` that gets triggered (for example, from a timeout), I notice that the query continues to run until it completes. If the processing takes longer than expected and the token is canceled, I then receive the `DbUpdateConcurrencyException` once the operation completes, even though the data is not being modified anymore. I've checked the EF Core version and confirmed it's the latest (6.0.0). I also verified that the cancellation is indeed being triggered because I see the cancellation request in the debugger. I expected that the `ToListAsync(cancellationToken)` would respect the cancellation request and abort the operation. Am I missing something in my approach? Is there a best practice for handling cancellation with EF Core queries that I should be following? Any insights would be greatly appreciated! This is part of a larger API I'm building. What am I doing wrong? I'm working in a Ubuntu 22.04 environment. What am I doing wrong? I'm developing on Ubuntu 22.04 with C#. I'd love to hear your thoughts on this.