How to update only changed values ​​(EntityFramework 5.0)?

I have this object that needs to be updated using entityframework

EmployeeModel employee = new EmployeeModel { Id = 1000, //This one must FirstName = modifiedValue, Email = modifiedValue, LastName = originalValue, Phone = originalValue }; 

Code for update

 _db.ObjectStateManager.ChangeObjectState(employee, EntityState.Modified); _db.SaveChanges(); 

This is the SQL expression received after the update.

 Update Employee set Id=1138,FirstName='modifiedValue',Email='modifiedValue',LastName= 'OriginalValue',phone='originalValue' where Id=1138 

But I expect this

 Update Employee set FirstName='modifiedValue', Email='modifiedValue' where Id=1138. 

I don’t know what is missing here. Please let me know.

+8
entity-framework-5 entity-framework
source share
2 answers

This is the solution I got

  var entity = _db.CreateObjectSet<Employee>(); entity.Detach(employee); entity.Attach(employee); foreach (string modifiedPro in employeeModel.ModifiedProperties){ _db.ObjectStateManager.GetObjectStateEntry(employee).SetModifiedProperty(modifiedPro);} _db.SaveChanges(); 

Only changed values ​​in sql update statement

 Update Employee set FirstName='modifiedValue', Email='modifiedValue' where Id=1138. 

If anyone knows the best answer, please write your suggestions.

+6
source share

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.

+8
source share

All Articles