It is written API application. There is a model that I am trying to update in the database:

public class Photo { public int Id { get; set; } public string Title { get; set; } public string Description { get; set; } public int Viewed { get; set; } } 

The Viewed field stores the number of views.

And there is a model

 public class PhotoForm { public int Id { get; set; } public string Title { get; set; } public string Description { get; set; } } 

well, action

 [HttpPost] public IActionResult Update([FromBody] PhotoForm photoForm) { var photo = _mapper.Map<Photo>(photoForm); _photoService.Update(photo); return Ok(photo); } 

and service

 public Photo Update(Photo photo) { _context.Update(photo); _context.SaveChanges(); return photo; } 

Well, and my problem, when updating so the number of views is reset, well, in general, everything that is not in the form, for example, the date of creation and other fields that should not be changed from the outside.

What am I doing wrong? Maybe you just need to look for a record by ID and manually transfer all values? Or mapper did not understand? How is this most beautiful done? And on the Internet some trivial records are updated everywhere.

    1 answer 1

    it seems like a string

     var photo = _mapper.Map<Photo>(photoForm); 

    Map all fields, including the empty ones, which will then be saved in the database.

    I decided by searching the record for Id, and already in it I update and save:

     var photo = _context.Photos.FirstOrDefault(p => p.Id == photoDto.Id); _mapper.Map(photoDto, photo); _context.SaveChanges();