I have this error and I can't figure out why it is happening. Can someone help out?
The instance of entity type 'ApplicationUser' 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.
I checked the previous answers and all of them say that somewhere another instance is being used. But I have simplified code to 2 lines in the controller. This must be somewhere else, but I don't know where to look.
{
[Route("api/user")]
[ApiController]
public class ApplicationUsersController : Controller
{
private readonly IEmailService _emailService;
private readonly IIdentityService _identityService;
private readonly IDbRepository<ApplicationUser> _userRepository;
private readonly IMapper _mapper;
private readonly UserManager<ApplicationUser> _userManager;
private readonly RoleManager<IdentityRole> _roleManager;
private readonly IConfiguration _configuration;
public ApplicationUsersController(
IDbRepository<ApplicationUser> userRepository,
IMapper mapper,
UserManager<ApplicationUser> userManager,
RoleManager<IdentityRole> roleManager,
IEmailService emailService,
IIdentityService identityService,
IConfiguration configuration)
{
_userRepository = userRepository ?? throw new ArgumentNullException(nameof(userRepository));
_mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));
_userManager = userManager ?? throw new ArgumentNullException(nameof(userManager));
_roleManager = roleManager ?? throw new ArgumentNullException(nameof(roleManager));
_emailService = emailService ?? throw new ArgumentNullException(nameof(emailService));
_identityService = identityService ?? throw new ArgumentNullException(nameof(identityService));
_configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
}
[HttpPut("{userId}")]
[Authorize(Roles = GlobalConstants.AdminRole + "," + GlobalConstants.ManagerRole + "," + GlobalConstants.AppraiserRole)]
public async Task<IActionResult> UpdatePasswordAndEmail([FromBody]
UserViewModel model, [FromRoute] string userId)
{
var user = await _userRepository.All().FirstOrDefaultAsync(x=>x.Id==userId);
var res1 = await this._userManager.RemovePasswordAsync(user); // THIS LINE GIVES ERROR
return Ok();
}
}
Any help appreciated
I am registering the context as follows:
builder.RegisterType<AmritaDbContext>().As<IAmritaDbContext>().InstancePerLifetimeScope();
builder.RegisterGeneric(typeof(DbRepository<>)).As(typeof(IDbRepository<>)).InstancePerLifetimeScope();`
Configure from startup:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
// app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseCors("CorsPolicy");
app.UseIdentityServer();
app.UseHttpsRedirection();
var option = new RewriteOptions();
option.AddRedirect("^$", "swagger");
app.UseRewriter(option);
app.UseStaticFiles();
ConfigureAuth(app);
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "api/v1/{controller=Home}/{action=Index}/{id?}");
});
var pathBase = Configuration["PATH_BASE"];
app.UseSwagger()
.UseSwaggerUI(c =>
{
c.SwaggerEndpoint($"{ (!string.IsNullOrEmpty(pathBase) ? pathBase : string.Empty) }/swagger/v1/swagger.json", "Amrita.API V1");
c.OAuthClientId("swaggerclient");
c.OAuthAppName("Amrita Swagger UI");
});
}
Configure from Identity Startup.cs
:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// InitializeIdentityServerDatabase(app);
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseIdentityServer();
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
}