更新默认 AspNetUsers 数据库中的自定义列数据 table

Update custom column data in default AspNetUsers database table

更新:

.net 5.0

我在我的 AspNetUsers 数据库中添加了一些自定义列。我现在正尝试从添加到脚手架 Identity Razor 页面的表单中填充这些列。

预期行为:

  1. 在注册页面点击提交
  2. 用户创建于 dbo.AspNetUsers
  3. 用户登陆注册确认页面
  4. 在注册确认页面点击提交
  5. 存储在 dbo.AspNetUSers table
  6. 中的自定义值
  7. 用户重定向到页面

实际行为:

  1. 在注册页面点击提交
  2. 用户创建于 dbo.AspNetUsers
  3. 用户登陆注册确认页面
  4. 在注册确认页面点击提交
  5. 自定义值 未存储 dbo.AspNetUSers table
  6. 用户重定向到页面

在“注册”页面上,我缓存了用户详细信息,以便我可以在下一页的数据库 table 中找到用户

        if (ModelState.IsValid)
        {
            DateTime SignedUpDateTime = DateTime.UtcNow;
            var user = new ApplicationUser { UserName = Input.Email, Email = Input.Email, SignedUp = SignedUpDateTime, TandC = Input.TOSAgree, MarketingComms = Input.MarketingComms };
            var result = await _userManager.CreateAsync(user, Input.Password);

            _cache.Set("User", user);

other code goes here...
}

注册确认页面我正在尝试保存名字。数据库中已存在新列。

   public async Task<IActionResult> OnPostAsync()
    {
        Debug.WriteLine("******************* On Post Async");

        using (ApplicationDbContext dbContext = new ApplicationDbContext())
        {
            ApplicationUser user = (ApplicationUser)_cache.Get("User");
            Debug.WriteLine("******************* user: " + user.ToString());
            var userId = user.Id.ToString();
            Debug.WriteLine("******************* userId: " + userId);

            user.FirstName = Input.FirstName;
            Debug.WriteLine("******************* FirstName: " + Input.FirstName);
            var name = dbContext.Users.SingleOrDefault(n => n.FirstName == Input.FirstName);
            Debug.WriteLine("******************* name: " + name);

            await dbContext.SaveChangesAsync();
        }
        Debug.WriteLine("******************* Return Page");

        return RedirectToPage("RegisterConfirmation", new { culture });
    }

调试日志输出:

Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker: Information: Executing handler method MyApp.Areas.Identity.Pages.Account.RegisterConfirmationModel.OnPostAsync - ModelState is Valid
******************* On Post Async
******************* user: myemail@email.com
******************* userId: e1234567-1234-1234-1234-0bbf3f123456
******************* FirstName: John
******************* name: 
******************* Return Page

终于想通了!

public async Task<IActionResult> OnPostAsync()
{
    using (ApplicationDbContext dbContext = new ApplicationDbContext())
    {
        ApplicationUser user = (ApplicationUser)_cache.Get("User");
        var userId = user.Id.ToString();

        var appUser = await dbContext.Users.FindAsync(userId);
        appUser.FirstName = Input.FirstName;

        await dbContext.SaveChangesAsync();
    }

    return RedirectToPage("RegisterConfirmation", new { culture });
}