我正在学习asp.net WebApi和EFCore (CodeFirst),作为练习,我正在构建仓库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,它运行没有任何错误,但它不更新我的数据库。
我是新手,所以这可能是一个容易的修复。
我正在使用这个通用的更新函数:
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;
}
难道你忘了在控制器端点调用你的服务方法吗?UpdateEmployee()
注释的解决方案工作,我只需要添加db.Entry(tmp).CurrentValues.SetValues(toUpdate)
到存储库代码。