The instance of entity type 'ApplicationUser' cannot be tracked because another instance with the same

时光总嘲笑我的痴心妄想 提交于 2020-07-10 10:27:30

问题


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();
        }

回答1:


That error implies that the services you provide for IDbRepository<ApplicationUser> userRepository and UserManager<ApplicationUser> userManager are using the same DbContext instance.

You need to change the scope in which the DbContext is registered.



来源:https://stackoverflow.com/questions/62640075/the-instance-of-entity-type-applicationuser-cannot-be-tracked-because-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!