Search code examples
asp.net-coreasp.net-identity

Identity UserManager UpdateAsync doesn't save custom fields to database


I've got a .NET Core 2 MVC project set up with AspNet Identity, using an ApplicationUser:

public class ApplicationUser : IdentityUser
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

In this action I get the FirstName and LastName from a form and want to save it to the database:

private readonly UserManager<ApplicationUser> _userManager;

...

var user = _userManager.GetUserAsync(User).Result;
user.FirstName = model.FirstName;
user.LastName = model.LastName;

var result = _userManager.UpdateAsync(user).Result;

Everything works (updating password, resetting password, etc.) except using _userManager.UpdateAsync(user) to save the custom fields. The returned result.Succeeded is always true, but the changes aren't saved to the database.

What am I doing wrong here?

Edit: the debug console outputs the following update-query for UpdateAsync, which lacks the custom fields:

UPDATE [AspNetUsers] SET [AccessFailedCount] = @p0, [ConcurrencyStamp] = @p1, [Email] = @p2, [EmailConfirmed] = @p3, [FirstName] = @p4, [LastName] = @p5, [LockoutEnabled] = @p6, [LockoutEnd] = @p7, [NormalizedEmail] = @p8, [NormalizedUserName] = @p9, [PasswordHash] = @p10, [PhoneNumber] = @p11, [PhoneNumberConfirmed] = @p12, [SecurityStamp] = @p13, [TwoFactorEnabled] = @p14, [UserName] = @p15


Solution

  • For completeness, I'll post my comment as an answer. The GetUserAsync function is still running when you set the FirstName and LastName. Adding await to the GetUserAsync method forces the code to wait for the Async function to complete before continuing.