InvalidOperationException when calling UserManager.UpdateAsync()
I have
public async Task<IActionResult> Edit(ApplicationUser model)
{
if (ModelState.IsValid)
{
var result = await _userManager.UpdateAsync(model);
if (result.Succeeded)
{
// do something
}
RedirectToAction("Index");
}
return View();
}
as my controller action. ModelState.IsValid is true. but when _userManager.UpdateAsync(model) executes, i get an error InvalidOperationException: The instance of entity type 'edu_app_01.Models.ApplicationUser' cannot be tracked because another instance of this type with the same key is already being tracked. For new entities consider using an IIdentityGenerator to generate unique key values.
I'm using roles in mu app, and user is added to a role.
_userManager object is injected in AccountController class constructor.
How can i resolve this?
This is unrelated to your question, but beware using your ApplicationUser in MVC's model binding as you might be subject to an underposting or overposting attack. You should use formal view models and update models, and not your EF model directly. And then, yes, you will have to map between them. Taking this approach will also mean you will avoid the issue that you're raising here.
@blowdart can provide some more official security guidance.
@brockallen I know that, this is actualy test code i made to examine another issue i have with UserManager<> class when running with Roles enabled.
When i try to _userManager.UpdateAsync(), i'm getting error that data can't be updated because [FK_IdentityUserRole<string>_ApplicationUser_UserId] conflict with AspNetUserRoles table.
@divega
@onedevteam re the original question, it is not possible for me to guess why it is failing for you without at least a full stack trace, but from what I see in the code the EF-specific part of the implementation of the UpdateAsync() method is designed to take a user object that is not currently tracked by the DbContext, mark it as modified and then save it to the database. It will fail if another object representing the same user (i.e. another instance with the same identifier) is already tracked in the DbContext, e.g. if any code retrieved or attached the user on the DbContext before UpdateAsyc() does it as part of your controller action.
Would it be possible for you to provide the stack trace and a more complete repro?
cc @HaoK
Feel free to reopen this if its still an issue and you have a stack trace/repro we can look at
I'm experiencing the same issue. I'm not using the context myself to retreive anything, just calling UpdateAsync. If I change the username field it works as expected, changing any other field causes the problem:
Here's the stack trace:
System.InvalidOperationException: The instance of entity type 'User' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap`1.Add(TKey key, InternalEntityEntry entry)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.StartTracking(InternalEntityEntry entry)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetEntityState(EntityState oldState, EntityState newState, Boolean acceptChanges)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetEntityState(EntityState entityState, Boolean acceptChanges, Boolean forceStateWhenUnknownKey)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityGraphAttacher.PaintAction(EntityEntryGraphNode node)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityEntryGraphIterator.TraverseGraph(EntityEntryGraphNode node, Func`2 handleNode)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityGraphAttacher.AttachGraph(InternalEntityEntry rootEntry, EntityState entityState, Boolean forceStateWhenUnknownKey)
at Microsoft.EntityFrameworkCore.DbContext.SetEntityState(InternalEntityEntry entry, EntityState entityState)
at Microsoft.EntityFrameworkCore.DbContext.SetEntityState[TEntity](TEntity entity, EntityState entityState)
at Microsoft.EntityFrameworkCore.DbContext.Attach[TEntity](TEntity entity)
at Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`9.<UpdateAsync>d__23.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at Microsoft.AspNetCore.Identity.UserManager`1.<UpdateUserAsync>d__171.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at Yangaroo.Awards.Admin.Application.UserManagement.Services.UserService.<SaveUserDetailsAsync>d__20.MoveNext() in C:\proj\AwardsV3\Yangaroo.Awards\Yangaroo.Awards.Admin.Application\UserManagement\Services\UserService.cs:line 277
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at Yangaroo.Awards.Admin.Web.Controllers.UsersController.<Put>d__9.MoveNext() in C:\proj\AwardsV3\Yangaroo.Awards\Yangaroo.Awards.Admin.Web\Controllers\UsersController.cs:line 82
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeActionMethodAsync>d__12.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeNextActionFilterAsync>d__10.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeInnerFilterAsync>d__14.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeNextResourceFilter>d__22.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeFilterPipelineAsync>d__17.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeAsync>d__15.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Builder.RouterMiddleware.<Invoke>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Yangaroo.Awards.Admin.Web.Infrastructure.Middleware.AntiForgeryMiddleware.<Invoke>d__3.MoveNext() in C:\proj\AwardsV3\Yangaroo.Awards\Yangaroo.Awards.Admin.Web\Infrastructure\Middleware\AntiForgeryMiddleware.cs:line 44
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Yangaroo.Awards.Admin.Web.Infrastructure.Middleware.ErrorMiddleware.<Invoke>d__3.MoveNext() in C:\proj\AwardsV3\Yangaroo.Awards\Yangaroo.Awards.Admin.Web\Infrastructure\Middleware\ErrorMiddleware.cs:line 46
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Yangaroo.Awards.Admin.Web.Infrastructure.Middleware.SpaFallbackMiddleware.<Invoke>d__5.MoveNext() in C:\proj\AwardsV3\Yangaroo.Awards\Yangaroo.Awards.Admin.Web\Infrastructure\Middleware\SpaFallbackMiddleware.cs:line 42
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Yangaroo.Awards.Admin.Web.Infrastructure.Middleware.MissingShowCodeMiddleware.<Invoke>d__4.MoveNext() in C:\proj\AwardsV3\Yangaroo.Awards\Yangaroo.Awards.Admin.Web\Infrastructure\Middleware\MissingShowCodeMiddleware.cs:line 44
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.<Invoke>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.<Invoke>d__7.MoveNext()