无法使用 Entity Framework 核心更新数据库

Can't Update database with Entity Framework Core

我正在学习 asp.net WebApi 和 EFCore (CodeFirst) 作为练习,我正在构建 Warehouse Api,但我的更新方法不起作用。 这是我的存储库代码:

public void Update(T toUpdate)
        {
            if(toUpdate == null) throw new ArgumentNullException("Entity is null");

            T tmp = GetById(toUpdate.Id);
            tmp = toUpdate;
            _context.SaveChanges();
        }

这是我的服务代码:

public void UpdateEmployee(UpdateEmployeeCommand command)
        {
            UpdateEmployeeCommandValidator validator = new UpdateEmployeeCommandValidator();
            var results = validator.Validate(command);
            if (!results.IsValid)
            {
                throw new CommandValidationException(results.Errors.Select(x => new CommandValidationError
                {
                    ErrorCode = x.ErrorCode,
                    ErrorMessage = x.ErrorMessage,
                    PropertyName = x.PropertyName
                }));
            }
            _repository.Update(new Employee()
            {
                Id = command.Id,
                FirstName = command.FirstName,
                Address = command.Address,
                LastName = command.LastName,
                Age = command.Age,
                Email = command.Email,
                PhoneNumber = command.PhoneNumber
            });
        }

这就是我在 Controller 中使用它的方式:

public ActionResult UpdateEmployee(int Id, UpdateEmployeeCommand command)
        {
            if(Id != command.Id)
            {
                return BadRequest();
            }
            var employeeModelFromRepo = _repository.GetById(Id);
            if(employeeModelFromRepo == null)
            {
                return NotFound();
            }

            _employeeService.UpdateEmployee(command);

            return NoContent();
        }

当我调用 UpdateEmployee 时,它​​运行没有任何错误,但它没有更新我的数据库。

我是新手,所以这可能很容易解决。

你是不是忘了在控制器端点调用你的服务方法? UpdateEmployee()

评论的解决方案有效,我只需要将 db.Entry(tmp).CurrentValues.SetValues(toUpdate) 添加到存储库代码中。

我正在使用这个通用更新功能:

public virtual T Update(T t) where T : class, IBaseEntity // contains Id as primary key
        {
            if (t == null)
                return null;
            var exist = Context.Set<T>().Find(t);

          // Or you can try 
           var exist = Context.Set<T>()
                    .Where(i=>i.Id=t.Id).FirstOrdDefault();

            if (exist == null) return exist;
            Context.Entry(exist).CurrentValues.SetValues(t);
            Context.SaveChanges();

            return exist;
        }