【问题标题】:ASP.NET Identity Update multiple tablesASP.NET Identity 更新多个表
【发布时间】:2019-07-04 11:32:54
【问题描述】:

我有两个数据库,一个处理用户身份验证(asp.net 默认身份表),另一个处理其他数据,该数据库也有一个自定义用户表。

我正在尝试更新 aspnetuser 表中的用户信息,这也将更新另一个数据库中的自定义用户表。我拥有的代码没有更新 aspnetuser 表中的必要字段,并在自定义用户表中创建了一条新记录,这不是所需的结果。以下是我到目前为止的代码。

    [HttpPut("{id}")]
    public async Task<IActionResult> Update(string id, ApplicationUser appUser)
    {

        if (!ModelState.IsValid)
        {
            return NotFound();
        }
        //locate appUser Id from AspNetUser table
        var user = await _userManager.FindByIdAsync(appUser.Id);

        if (user == null)
        {
            return NotFound();
        }
        //locate email address that exists in the custom User table
        var contextUser = _context.UserTable.Where(u => u.Email == appUser.Email);

        if (contextUser == null)
        {
            return NotFound();
        }

        if (ModelState.IsValid)
        {
            try
            {
                await _userManager.UpdateAsync(appUser);

                UserTable personInfo = new User();
                personInfo.FirstName = appUser.FirstName;
                personInfo.LastName = appUser.LastName;
                personInfo.EmailAddress = appUser.Email;

                _context.UserTable.Update(personInfo);
                await aspnetdBContext.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {

            }
        }
        return Ok(appUser);

当我通过邮递员进行测试时,我得到一个 Ok 200 代码,其中包含更改后的 json 结果。 aspnetuser 表仍未更新必填字段。它也不会在自定义用户表中定位用户。我哪里错了?

【问题讨论】:

  • hmm.. 我没有在核心工作太多,但是 asp.net 身份与您的功能范围并不真正相关。它似乎更像是一个实体框架问题。它归结为您对上下文和实体的理解,它们本质上是上下文绑定模型。在这种情况下,您没有修改实体(这需要您查询实体,更改实体属性,通过将其传回进行更新,然后保存)并且我看不到您在此处处理 aspnetdBContext 的任何实体.

标签: c# asp.net asp.net-web-api asp.net-identity


【解决方案1】:

您应该使用从数据库中检索到的用户来防止在您的表中创建新用户,无需使用new 创建用户

//UserTable personInfo = new User();
contextUser.FirstName = appUser.FirstName;
contextUser.LastName = appUser.LastName;
contextUser.EmailAddress = appUser.Email;

这将帮助您更新自定义用户表。

【讨论】:

    【解决方案2】:

    我相信 UserTable 和 AppUser 表是一对一相关的,或者在这种情况下可能是一对多,如果 User 表和 appuser 表相关,那么您可以将代码简化为

       try
                {
                    appUser.personInfo.FirstName = appUser.FirstName;
                    appUser.personInfo.LastName = appUser.LastName;
                    appUser.personInfo.EmailAddress = appUser.Email;
                    await _userManager.UpdateAsync(appUser); 
                    await aspnetdBContext.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
    
                }
    

    您可能想研究 ef Lazyloading 和 eagerLoading 概念,以更好地了解它们的工作原理

    【讨论】:

      猜你喜欢
      • 2014-05-15
      • 2014-05-16
      • 1970-01-01
      • 2016-11-09
      • 2014-08-26
      • 2018-12-01
      • 1970-01-01
      • 2016-10-22
      • 1970-01-01
      相关资源
      最近更新 更多