Using Entity Framework in a Blazor Server Application

When running Entity Framework (EF) through a Blazor Server application, you may get the following error:

InvalidOperationException: A second operation started on this context before a previous operation completed. This is usually caused by different threads using the same instance of DbContext.

The cause of this error is having multiple Razor components, overriding asynchronous methods such as OnInitializedAsync, and using Entity Framework within them.

Entity Framework’s default service scope is Scoped, which means it’s only allowed to be used once at any time per thread.

I will run you through two ways of fixing this error. The first way is to change Entity Framework’s service scope to Transient. The other way is to create localised scopes per Razor component.

Either fix works, but I do have a preference which I will share in the video.

► More Information:

#aspnetcore #entityframework #blazorserver

Using Entity Framework in a Blazor Server Application