【问题标题】:ASP.NET Core Identity : a second operation started on this context before a previous operation completedASP.NET Core Identity :在前一个操作完成之前在此上下文上启动了第二个操作
【发布时间】:2020-05-31 15:32:42
【问题描述】:

我收到一个错误:

在前一个操作完成之前在此上下文上启动了第二个操作

当我尝试使用AddToRoleAsync 函数添加用户角色时。我看到很多帖子说缺少等待,但一切都是正确的。下面是我正在使用的代码。

public async Task<IActionResult> RegisterCustomer(UserForRegisterCustomerDto userForRegisterCustomerDto)
{
        userForRegisterCustomerDto.UserName = userForRegisterCustomerDto.Email;

        var userToCreate = _mapper.Map<Users>(userForRegisterCustomerDto);

        var userVehicleToCreate = _mapper.Map<CustomerVehicles>(userForRegisterCustomerDto.CustomerVehicles);



        var result = await _userManager.CreateAsync(userToCreate, userForRegisterCustomerDto.Password);

        var userToReturn = _mapper.Map<UserForDetailedDto>(userToCreate);

        if (result.Succeeded)
        {
            var currentUser = await _userManager.FindByEmailAsync(userForRegisterCustomerDto.Email);
            await _userManager.AddToRoleAsync(currentUser, "Customer");
            userVehicleToCreate.UserId = currentUser.Id;

            _repo.Add(userVehicleToCreate);

            if (await _repo.SaveAll())
            {
                string confirmationToken = await _userManager.GenerateEmailConfirmationTokenAsync(currentUser);
                //ConfirmEmail(currentUser.Id, confirmationToken);
                return Ok(userToReturn);
            }
        }

        return BadRequest(result.Errors);
    }

我的 Startup.cs 是

services.AddDbContext<DataContext>(x => x.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")), ServiceLifetime.Transient);

添加 ServiceLifetime.Transient 并不能解决此问题。请提出建议。

错误是:

 Microsoft.EntityFrameworkCore.Query[10100]
      An exception occurred while iterating over the results of a query for context type 'Demo.API.Models.DataContext'.
      System.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. For more information on how to avoid threading issues with DbContext, see https://go.microsoft.com/fwlink/?linkid=2097913.
         at Microsoft.EntityFrameworkCore.Internal.ConcurrencyDetector.EnterCriticalSection()
         at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
System.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. For more information on how to avoid threading issues with DbContext, see https://go.microsoft.com/fwlink/?linkid=2097913.
   at Microsoft.EntityFrameworkCore.Internal.ConcurrencyDetector.EnterCriticalSection()
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
      An unhandled exception has occurred while executing the request.
System.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. For more information on how to avoid threading issues with DbContext, see https://go.microsoft.com/fwlink/?linkid=2097913.
   at Microsoft.EntityFrameworkCore.Internal.ConcurrencyDetector.EnterCriticalSection()
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
   at Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.SingleOrDefaultAsync[TSource](IAsyncEnumerable`1 asyncEnumerable, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.SingleOrDefaultAsync[TSource](IAsyncEnumerable`1 asyncEnumerable, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`9.IsInRoleAsync(TUser user, String normalizedRoleName, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Identity.UserManager`1.AddToRoleAsync(TUser user, String role)
   at Demo.API.Controllers.AuthController.RegisterCustomer(UserForRegisterCustomerDto userForRegisterCustomerDto) in F:\test\Demo\Demo.API\Controllers\AuthController.cs:line 66
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker,
Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task
lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

【问题讨论】:

  • 你在使用unitOfWork吗?

标签: c# asp.net-core asp.net-identity


【解决方案1】:

然后添加它

services.AddDbContext<DataContext>(x => x.UseSqlServer(Configuration
.GetConnectionString("DefaultConnection")).UseQueryTrackingBehaviour(QueryTrackingBehavior.NoTracking));

【讨论】:

  • System.InvalidOperationException:无法跟踪实体类型“Users”的实例,因为已经在跟踪具有相同键值 {'Id'} 的另一个实例。附加现有实体时,请确保仅附加一个具有给定键值的实体实例。考虑使用“DbContextOptionsBuilder.EnableSensitiveDataLogging”来查看冲突的键值。
【解决方案2】:

问题出在您创建模型的方式上。

解决方案:处理 NULL 字段并检查模型。

如果您在 _Layout 视图中对诸如 Login、Username、SignInManager 或其他与类和模型相关的字段进行操作,请检查它们...错误会由此产生。

【讨论】:

    猜你喜欢
    • 2018-11-07
    • 2020-09-30
    • 2020-11-06
    • 2022-01-01
    • 1970-01-01
    • 2020-12-18
    • 1970-01-01
    • 2018-07-23
    • 1970-01-01
    相关资源
    最近更新 更多