【问题标题】:.NET CORE 3.1, MVC Async method not updating DB.NET CORE 3.1,MVC 异步方法不更新数据库
【发布时间】:2020-07-26 13:00:35
【问题描述】:

AI 正在转向 ASYNC 方法并尝试更新我的数据。我可以选择只是查找,这样我就知道存储库正在运行。

动作

    [HttpPost]
    public async Task<IActionResult> EditTeam(EmployeeVm empVm)
    {
        if (!ModelState.IsValid)
        {
            ModelState.AddModelError("", _errorUpdateMsg);
        }
        else
        {
            if (await _teamRepository.UpdateEmployee(empVm.Employee))
            {
                return RedirectToAction("Index");
            }

            ModelState.AddModelError("", _errorUpdateMsg);
        }

        return View(empVm);
    }  

我在 repo 中的构造函数

    public TeamRepository(EnvisionDbContext envisionDbContext)
    {
        _envisonDbContext = envisionDbContext;
    }

这是我没有保存的更新

    public async Task<bool> UpdateEmployee(Employee employee)
    {
        var result = await _envisonDbContext.Employees.FirstOrDefaultAsync<Employee>(e => e.Id == employee.Id);

        if (result != null)
        {
            result.FirstName = employee.FirstName;
            result.LastName = employee.LastName;
            result.Phone = employee.Phone;
            result.IsActive = employee.IsActive;

            await _envisonDbContext.SaveChangesAsync();

            return true;
        }

        return false;
    }

提前感谢您的帮助。

更新:如果我添加这个,它会起作用。这是因为两个 await 调用断开了吗?

            result.IsActive = employee.IsActive;
            _envisonDbContext.Entry(result).State = EntityState.Modified;

【问题讨论】:

  • 您在日志记录中看到了什么?您是否尝试过分析数据库?

标签: asp.net-mvc asp.net-core async-await


【解决方案1】:

好像你在保存更改之前忘记了更新方法

if (result != null)
    {
        result.FirstName = employee.FirstName;
        result.LastName = employee.LastName;
        result.Phone = employee.Phone;
        result.IsActive = employee.IsActive;

        _envisionDbContext.Update(result); //paste it before you save changes

        await _envisonDbContext.SaveChangesAsync();

        return true;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-28
    • 2021-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多