error a second operation was started on this context in blazor

Mahdi Elahi 31 Reputation points
2024-02-09T01:00:56.02+00:00

Hi in Books.razor Component , this is my Adaptor.cs , Books.razor , Service and Repository
my problem is when i Update a record in Edit.razor when the record is updated i navigate to books.razor but when navigate to books.razor ,
it's get book Status On OnInitializedAsync then go to Adaptor to get the grid data in repository when but request to database it's show this error :
a second operation was started on this context instance before a previous operation completed. this is usually caused by different threads concurrently using the same instance of dbcontext. for more information on how to avoid threading issues with dbcontext 1.i check the async / await
2.change program.cs to : builder.Services.AddDbContext(options => options.UseSqlServer(connectionString),ServiceLifetime.Transient); and then change again to and test it builder.Services.AddDbContext(options => options.UseSqlServer(connectionString),ServiceLifetime.Scoped); but it's not worked and show error again Note : When i Remove these codes in books.razor it's worked

   ScrambleStatus = await scrambleService.GetStatus();
   ScrambleStatus.Insert(0, "All");
   SelectedStatus = ScrambleStatus.First(); Copy

is problem on my call async / await ?
what's problem ?

Developer technologies | ASP.NET | ASP.NET Core
Developer technologies | .NET | Blazor
{count} votes

2 answers

Sort by: Most helpful
  1. AgaveJoe 30,126 Reputation points
    2024-02-09T13:19:22.9066667+00:00

    Registering a scoped service in Blazor server means the service is shared across all components within the user's circuit. The DbContext is not thread safe so special care must be taken when dealing with the DbContext in server-side Blazor applications.

    ASP.NET Core Blazor with Entity Framework Core (EF Core)

    Handling the DbContext was discussed in one of your previous threads where the same link was provided. I do not see where your source code is following the recommended coding patterns.
    https://learn.microsoft.com/en-us/answers/questions/1499772/blazor-net-8-cannot-access-a-disposed-context-inst

    0 comments No comments

  2. Bruce (SqlWork.com) 78,006 Reputation points Volunteer Moderator
    2024-02-11T21:45:57.3266667+00:00

    With blazor server, you should use a dbcontext factory or transient , not an scoped lifetime. This is because all components share the same scoped context for the life of the app, and if you use async components, two can access the dbcontext at the same time.

    note: dispose just calls close() which releases unmanaged resources. Dispose is handy because you can use the using statement

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.