首页 > 解决方案 > 如何在 ASP.NET Core Web API 中更新 AppDBContext

问题描述

我对 ASP.NET 很陌生,对此我有点坚持。我在注册用户时在我的数据库中创建一个条目:

private async Task<bool> CreateEntryInUserActions(AppUser user)
        {
                var entity = new UserActionEntity
                {
                    UserId = user.Id,
                };

                await _context.tbl_UserActions.AddAsync(entity);
                await _context.SaveChangesAsync();

                return true;
         }

当用户更改他/她的密码时,我想将 UserActions 表中的 IsPasswordChanged 字段更改为 true。我正在尝试类似的东西:

private async Task<bool> UpdateUserAction()
        {
            var userId = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value; // gives me current user's id

            var user = _context.tbl_UserActions
                .Where(x => x.UserId.ToString() == userId).Select(x => x.IsPasswordChanged);

        }

但我不确定如何继续并将其更新为“true”。如何更新此条目?

标签: asp.net-coreasp.net-web-apientity-framework-core

解决方案


您需要从表中获取 useraction 实体,然后将 IsPasswordChanged 属性设置为 true。

尝试这个:

private async Task<bool> UpdateUserAction()
    {
        var userId = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value; // gives me current user's id

        var user = _context.tbl_UserActions.FirstOrDefault(x => x.UserId.ToString() == userId);
        if(user != null) //check if the record is not null
        {
            user.IsPasswordChanged = true; // set the column to desired value
            _context.tbl_UserActions.Update(user);
            await _context.SaveChangesAsync();
         }

    }

推荐阅读