Skip to content

Fix S6966 FP: EntityFrameworks IDbContextFactory CreateDbContext method is preferred over its Async counterpart #9590

@manuel-rw

Description

@manuel-rw

Description

Rule ID: S6966

As documented in dotnet/efcore#26630, the CreateDbContextAsync() is a method for special edge cases only.
The synchronous CreateDbContext() is preferred for most cases. This has been reflected in updated rules in the Roslyn analyzers: dotnet/roslyn-analyzers#7036

However, Sonar currently emits S6966 for any usage of the CreateDbContext() method.

Repro steps

public class DependencyInjectedService
{
  private readonly IDbContextFactory<AppDbContext> _factory;

  public DependencyInjectedService(IDbContextFactory<AppDbContext> factory)
  {
    _factory = factory;
  }
  
  public async Task DoSomeWork()
  {
    using AppDbContext dbContext = _factory.CreateDbContext(); // Awaitable method should be used csharpsquid:S6966
  }
}

public class AppDbContext : DbContext
{
}

Expected behavior

Since CreateDbContext is preferred Sonar should not emit a diagnostic warning.

Actual behavior

Sonar emits the S6966 warning and proposes the CreateDbContextAsync method instead.

Known workarounds

  1. Disable the rule -> also disables the check for all other methods
  2. Create a custom extension method which wraps any calls to CreateDbContext() and ignores the warning on this specific line. Obvious disadvantage being that the efcore API is being hidden and additional complexity is being introduced.

Related information

  • C#/VB.NET Plugins version: C# 9.27 (build 93347), VB 9.27 (build 93347)
  • Visual Studio version: Using Rider, but irrelevant for this ticket -> build and Sonar is executed within pipeline
  • MSBuild / dotnet version: msbuild 7.1.1 / .NET 8.0.303
  • SonarScanner for .NET version:
  • Operating System: Windows 11, 23H2 (64bit)

Metadata

Metadata

Labels

False PositiveRule IS triggered when it shouldn't be.

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions