A note on async methods

From Bitnami MediaWiki
Revision as of 15:03, 10 October 2023 by User (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
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