Cadmi
Cadmi

Reputation: 73

EF 6, Update Entity from DTO, but only existing properties (generic code)

I'd like to know the best way to update an Entity retrieved from the DB. The front-end requests an update for an entity, sending a DTO which contains the id of the entity, and also some fields. Then with this Id, I look for the entity in the DB, and here comes the question:

I want to update the fields of the entity which are set in the DTO, and keep the other fields. Obviously I can do it explicitly, field by field, but I'd like to know a best practise to do it in a generic way for all the properties of the DTO.

The code would look like:

[HttpPut]
public IActionResult Put([FromBody]PersonDTO pDTO) {
   Person p = GetPersonById(pDTo.IdPerson);
   p.Name = pDTO.Name;
   p.Address = pDTO.Address;
   // and 100 more fields
   _context.SaveChanges();
}

How can I avoid the mapping between the DTO and the Model? I though about using reflection, but i can't find out if there is a better, more elegant, and standard way to do it.

Thanks

Upvotes: 0

Views: 3669

Answers (1)

Adam Stawarek
Adam Stawarek

Reputation: 331

I think the most popular choice in c# when it comes to mapping objects is to use AutoMapper, http://automapper.org/

Person person = Mapper.Map<Person>(pDTO);

Upvotes: 3

Related Questions