我有一个用于编辑ApplicationUser
对象的页面。这是来自IdentityUser
的简单继承,带有一些其他字段。
这些类对各种管理器使用注入,并为表单和处理定义绑定的CurrUser。
public class UserEditModel : CtrackPageModel
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly RoleManager<ApplicationRole> _roleManager;
private readonly ApplicationDbContext _db;
private readonly ILogger<UserEditModel> _logger;
public UserEditModel(
ApplicationDbContext db,
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
RoleManager<ApplicationRole> roleManager,
ILogger<UserEditModel> logger)
{
_db = db;
_userManager = userManager;
_signInManager = signInManager;
_roleManager = roleManager;
_logger = logger;
}
[BindProperty]
public ApplicationUser CurrUser { get; set; }
public IList<Organisation> Organisations { get; set; }
OnGetAsync
仅加载选择列表的值并设置CurrUser
public async Task<IActionResult> OnGetAsync(string id)
{
CurrUser = await _userManager.FindByIdAsync(id);
Organisations = await _db.Organisations.AsNoTracking().ToListAsync();
if (CurrUser == null)
{
_logger.LogWarning("User not defined. Redirecting to /Admin/Users");
return RedirectToPage("/Admin/Users");
}
return Page();
}
OnPostEditAsync最初看起来像在工作。调试时,我可以看到CurrUser对象存在并已填充请求的更改。
public async Task<IActionResult> OnPostEditAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
Organisations = await _db.Organisations.AsNoTracking().ToListAsync();
try
{
_logger.LogInformation("Attempting to update User.");
IdentityResult result = await _userManager.UpdateAsync(CurrUser);
if (result == IdentityResult.Success)
{
_logger.LogInformation($"Modified User {CurrUser.UserName}");
AlertInformation($"Modified User {CurrUser.UserName}.");
}
else
{
_logger.LogInformation($"Error modifying User {CurrUser.UserName}. Result status is {result.ToString()}.");
AlertError($"Error modifying User {CurrUser.UserName}. Result status is {result.ToString()}.");
}
return Page();
}
catch (Exception ex)
{
_logger.LogError(ex, $"Error modifying User {CurrUser.UserName}");
AlertError($"Error modifying User {CurrUser.UserName}. Exception is {ex.GetType()}.");
if(User.IsInRole("Admin"))
{
AlertException(ex);
}
}
return Page();
}
但是,在进行_userManager.UpdateAsync(CurrUser);
调用时,它将引发以下异常
System.InvalidOperationException
无法跟踪实体类型'ApplicationUser'的实例,因为已经跟踪了具有相同键值的{'Id'}的另一个实例。附加现有实体时,请确保仅附加一个具有给定键值的实体实例。考虑使用'DbContextOptionsBuilder.EnableSensitiveDataLogging'查看冲突的键值。
Microsoft.EntityFrameworkCore