无法跟踪实体类型"ApplicationUser"的实例,因为另一个具有相同实例的实例 [英] The instance of entity type 'ApplicationUser' cannot be tracked because another instance with the same
问题描述
我有这个错误,我不知道为什么会发生.有人可以帮忙吗?
I have this error and I can't figure out why it is happening. Can someone help out?
无法跟踪实体类型'ApplicationUser'的实例,因为已经跟踪了另一个具有相同键值的{'Id'}实例.附加现有实体时,请确保仅附加一个具有给定键值的实体实例.考虑使用'DbContextOptionsBuilder.EnableSensitiveDataLogging'查看冲突的键值.
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.
我检查了先前的答案,所有的答案都说正在某个地方使用另一个实例.但是我已经将代码简化为控制器中的2行.这肯定是在其他地方,但我不知道在哪里看.
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();
}
}
任何帮助表示赞赏
我正在注册上下文,如下所示:
I am registering the context as follows:
builder.RegisterType<AmritaDbContext>().As<IAmritaDbContext>().InstancePerLifetimeScope();
builder.RegisterGeneric(typeof(DbRepository<>)).As(typeof(IDbRepository<>)).InstancePerLifetimeScope();`
从启动配置:
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");
});
}
从身份Startup.cs
配置:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// InitializeIdentityServerDatabase(app);
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseIdentityServer();
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
}
推荐答案
该错误表示您为IDbRepository<ApplicationUser> userRepository
和UserManager<ApplicationUser> userManager
提供的服务正在使用相同的DbContext
实例.
That error implies that the services you provide for IDbRepository<ApplicationUser> userRepository
and UserManager<ApplicationUser> userManager
are using the same DbContext
instance.
您需要更改DbContext的注册范围.
You need to change the scope in which the DbContext is registered.
这篇关于无法跟踪实体类型"ApplicationUser"的实例,因为另一个具有相同实例的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!