This problem is common when working with DTO. The employee object is retrieved from the database, mapped to the DTO, and sent over the network. The client then modifies this DTO and sends it back to the server.
When you touch (set) a property of an EF object, EF will assume that the value has been changed. Even if the old value and the new value exactly match. The same problem occurs when you map a DTO to a new Entity and attach it to an EF and update its status to Modified.
Using AutoMapper:
// This will result in the full update statement var employee = AutoMapper.Mapper.Map<EmployeeDto, Employee>(dto); // This will result in a smaller update statement (only actual changes) var employee = dbContext.Employees.Find(dto.Id); AutoMapper.Mapper.Map(dto, employee);
Or manually (I wouldnβt do this, but only for the sake of completeness):
// This will result in a smaller update statement (only actual changes) var employee = dbContext.Employees.Find(dto.Id); if (employee.Email != dto.Email ) employee.Email = dto.Email;
There are probably some other solutions to this problem ... but using AutoMapper together with the Entity Framework correctly is certainly one of the easiest ways.
deherch
source share