Skip to content

0xced/WorkaroundSqlClientIssue26

Repository files navigation

Work around Microsoft SqlClient issue #26 for EF Core

NuGet Continuous Integration Coverage

Microsoft's SqlClient has a long standing issue (#26): Cancelling an async SqlClient operation throws SqlException, not TaskCanceledException

It is problematic because whenever an SQL command is canceled, an InvalidOperationException, a SqlException or a TaskCanceledException will be randomly thrown . This is also a showstopper when using Blazor virtualization where an OperationCanceledException is expected to signal cancelation.

This project provides a workaround that leverages EF Core execution strategies. When using this workaround, querying the db context will consistently throw an OperationCanceledException upon cancelation.

try
{
  await dbContext.Tracks.CountAsync(cancellationToken);
}
catch (OperationCanceledException ex) when (ex.CancellationToken == cancellationToken)
{
  // Alwas caught with the workaround applied. Uncaught with SqlClient default behavior.
}

Getting started

Add the WorkaroundSqlClientIssue26 NuGet package to your project using the NuGet Package Manager or run the following command:

dotnet add package WorkaroundSqlClientIssue26

Install the workaround when configuring the db context options.

var options = new DbContextOptionsBuilder<MyDbContext>()
  .UseSqlServer(connectionString, sql => sql.WorkAroundSqlClientIssue26())
  .Options;

This workaround is also compatible with a custom execution strategy such as retry on failure.

var options = new DbContextOptionsBuilder<MyDbContext>()
  .UseSqlServer(connectionString, s => s.EnableRetryOnFailure().WorkAroundSqlClientIssue26())
  .Options;

Frequently Asked Questions

  • What are the supported EF Core versions?

    • EF Core 8, 9 and 10 are supported. Future versions should work too.
  • Why is this package required? Why doesn't EF Core take care of throwing a proper OperationCanceledException?

    • EF Core distinguishes cancelation from failure, but only for logging purposes. A maintainer of EF Core said this:

      EF makes no attempt to correct SqlClient's behavior here by throwing a different type of exception; it just distinguishes between failure and cancellation.

  • What happens if the original issue gets fixed?

    • If SqlClient issue #26 is fixed, this workaround will turn into a no-op.

About

Work around Microsoft SqlClient issue #26 (incorrect cancellation behaviour)

Resources

License

Code of conduct

Stars

Watchers

Forks

Packages

 
 
 

Contributors

Languages