Method returns before await finishes executing

Solution 1:

You must use IDbContextFactory if you are using Blazor server-side, because you can't use the same dbcontext instance multiple times in multiple threads.

Your dbcontext service is scoped, which means it will create a new instance while the new request to the server, but the Blazor server is a single page application and you have a single request and single dbcontext instance, and if you use the same dbcontext like a normal asp.net core application it will give you this error:

Error: System.InvalidOperationException: A second operation was started on this....

You must create dbcontext instances manually. Register your dbcontext like this:

builder.Services.AddDbContextFactory<MyDbContext>(
     options => options.UseSqlServer(builder.Configuration.GetConnectionString("myConnectionString")));

and use it in your code like this:

private readonly IDbContextFactory<MyDbContext> _contextFactory;

public MyController(IDbContextFactory<MyDbContext> contextFactory)
{
    _contextFactory = contextFactory;
}

public void DoSomething()
{
    using (var context = _contextFactory.CreateDbContext())
    {
        // ...
    }
}

You can read more in DbContext Lifetime, Configuration, and Initialization.