0

I want to update my entity for just sending values.

public HttpResponseMessage UpdateDepartment(Department department)
{
    var ok = _departmentDAL.Update(department);
    return Request.CreateResponse(HttpStatusCode.OK, ok);
}

Im sending just 2 value with postman to my api. postman

In my generic repository base, my update function like.

public int Update(TEntity entity)
{
    var updatedEntity = _context.Entry(entity);
    updatedEntity.State = EntityState.Modified;

    return _context.SaveChanges();
}

And I got entity validation error. Simply I just want to modify only not null values of entity.

Is it possible or should I take all entity with my Id property from database and then after changing the properties send to the entity framework ?

cpzz
  • 55
  • 11
  • Possible duplicate of [How to update only one field using Entity Framework?](https://stackoverflow.com/questions/3642371/how-to-update-only-one-field-using-entity-framework) – Peter B Apr 03 '18 at 12:31

1 Answers1

0

Cleanest solution is to not provide a general interface that can update any desired field of Department. Instead, provide an API that is tailored to the actual use cases you want to support. This API should receive commands that only contain the data allowed for the specific use case. Commands can also validate their data (here I use System.ComponentModel.DataAnnotations for validation). Also, you can handle authorization in a more granular way if the use cases are well defined and separated.

public class UpdateDepartmentDescriptionCommand {

    [Required, Range(1, long.MaxValue)]
    public long DepartmentId { get; set; }

    [Required, StringLength(256)]
    public string Description { get; set; }
}

public HttpResponseMessage UpdateDepartmentDescription(UpdateDepartmentDescriptionCommand cmd) {

    // validate command
    var validationResults = new List<ValidationResult>();
    var isValid = Validator.TryValidateObject(cmd, new ValidationContext(cmd, null, null), validationResults, true);

    if (!isValid) {
        return Request.CreateResponse(HttpStatusCode.BadRequest, validationResults);
    }

    // retrieve Department from DB using the given ID
    var department = _departmentDAL.Find(cmd.DepartmentId);

    // only update values defined by the usecase
    department.Description = cmd.Description;

    var ok = _departmentDAL.Update(department);
    return Request.CreateResponse(HttpStatusCode.OK, ok);
}
Georg Patscheider
  • 9,357
  • 1
  • 26
  • 36