A note on async methods

From Bitnami MediaWiki
Jump to navigation Jump to search

Within an async method, you may get an exception message "A second operation started on this context before a previous operation completed" when running some EF Core queries. It probably occurs when the LINQ expression may execute another query such as a semi-join:

await UOW.GlCharts
  .QueryNoTracking(g => UOW.GlControls
  .Any(c => g.GlAccount == c.GlErrorMissingAccount)
  )
  .SingleOrDefaultAsync();

The above code may throw the exception since the UoW is referenced again.

await UOW.GlCharts
  .QueryNoTracking(g => dbContext.GlControl
    .Any(c => g.GlAccount == c.GlErrorMissingAccount)
  )
  .SingleOrDefaultAsync();

To solve the issue, the code above uses the DB context directly inside the LINQ expression instead of the UoW.


Return to Programming Guide