2022-01-19

Method returns before await finishes executing

I am listing data with Blazor server side and MudBlazor.
I have a user list:

UserList.razor

public partial class UserList
{
    private async Task<TableData<User>> ServerReload(TableState state)
    {
        var admTableData = await _userService.GetUsersAsTableDataAsync(state.ToAdmTableState());
        return admTableData.ToTableData();
    }
}

The service for the user list looks like this:

UserService.cs

public class UserService
{
    public UserService(MyDbContext myDbContext)
    {
        _userRepository = new UserRepository(myDbContext);
    }

    public Task<AdmTableData<User>> GetUsersAsTableDataAsync(AdmTableState admTableState)
    {
        var queryable = _userRepository.GetUsersAsQueryable();

        if (!string.IsNullOrEmpty(admTableState.SearchString))
        {
            queryable = queryable.Where(u => u.Name.Contains(admTableState.SearchString, StringComparison.OrdinalIgnoreCase));
        }

        switch (admTableState.SortLabel)
        {
            case "Name":
                queryable = queryable.OrderByDirection(admTableState.SortDirection, o => o.Name);
                break;
        }

        return PaginationHelper.GetTableDataAsync(queryable, admTableState);
    }
}

The pagination helper:

PaginationHelper.cs

public static async Task<AdmTableData<T>> GetTableDataAsync<T>(IQueryable<T> queryable, AdmTableState admTableState)
{
    var admTableData = new AdmTableData<T>();

    admTableData.TotalItems = await queryable.CountAsync();

    admTableData.Items = await queryable.Skip(admTableState.PageNumber * admTableState.PageSize)
        .Take(admTableState.PageSize).ToListAsync();

    return admTableData;
}

Lastly. I am registering the services in the following way:

Program.cs

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

builder.Services.AddScoped<IUserService, UserService>();

If I order a column. I get this error:

Error: System.InvalidOperationException: 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, see https://go.microsoft.com/fwlink/?linkid=2097913.

If I do a search. It never gets the data and it keeps loading:

Loading forever screenshot



from Recent Questions - Stack Overflow https://ift.tt/3I0celI
https://ift.tt/eA8V8J

No comments:

Post a Comment