简体   繁体   中英

Changes to ApplicationUser property are not written to the database

I have code in my controller to disable an account. The code was working fine. Now, all of a sudden it isn't.

public async Task<ActionResult> DisableClient(string userId, int disableAccount)
{
    bool disable = (disableAccount != 0);
    ApplicationUser user = UserManager.FindById(userId);
    if (user != null && user.Disabled != disable)
    {
        user.UserName = disable ? DisabledUserName : user.Email;   // Not sure if this is needed
        user.Disabled = disable;
        // Generating a new security stamp invalidates the user's
        // session, effectively locking them out
        if (user.Disabled)
            await UserManager.UpdateSecurityStampAsync(userId);
        await UserManager.UpdateAsync(user);
    }
    return RedirectToAction("Details", "Client", new { userId = userId });
}

ApplicationUser.Disabled was mapping to AspNetUsers.Disabled . But now, I can see the code above setting this property to true , but the value in the database remains false .

I don't understand how this could've changed. Can anyone help explain this?

I figured it out. I tried adding the following line to ensure the database context was saving the changes.

HttpContext.GetOwinContext().Get<ApplicationDbContext>().SaveChanges();

However, this line caused an exception because my code had produced a duplicate value in an indexed column.

I now assume that my original code was also producing an exception, but it was handled silently. The line above is not needed. As long as there is no hidden exception, my original code works fine. And this explains why it was working but then stopped: Because it had to have two accounts disabled before there was a duplicate that causes the exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM