Blazor concurrency problem using Entity Framework Core

后端 未结 6 1533
半阙折子戏
半阙折子戏 2021-01-05 03:46

My goal

I want to create a new IdentityUser and show all the users already created through the same Blazor page. This page has:

  1. a form
6条回答
  •  一生所求
    2021-01-05 04:35

    I found your question looking for answers about the same error message you had.

    My concurrency issue appears to have been due to a change that triggered a re-rendering of the visual tree to occur at the same time as (or due to the fact that) I was trying to call DbContext.SaveChangesAsync().

    I solved this by overriding my component's ShouldRender() method like this:

        protected override bool ShouldRender()
        {
            if (_updatingDb)
            { 
                return false; 
            }
            else
            {
                return base.ShouldRender();
            }
        }
    

    I then wrapped my SaveChangesAsync() call in code that set a private bool field _updatingDb appropriately:

            try
            {
                _updatingDb = true;
                await DbContext.SaveChangesAsync();
            }
            finally
            {
                _updatingDb = false;
                StateHasChanged();
            }
    

    The call to StateHasChanged() may or may not be necessary, but I've included it just in case.

    This fixed my issue, which was related to selectively rendering a bound input tag or just text depending on if the data field was being edited. Other readers may find that their concurrency issue is also related to something triggering a re-render. If so, this technique may be helpful.

提交回复
热议问题