Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get Entity Framework to only update the Properties modified in the SQL generated?

I am using Entity Framework with the Self-Tracking Entity T4 templates, which by default will generate a SQL Query setting all the properties on the Entity in an UPDATE statement. I only want an UPDATE statement that contains the properties modified.

I modified the T4 Template as specified in the book: Entity Framework Recipes: A Problem-Solution Approach page 503.

I changed to this line in the T4 Template:

OriginalValueMembers originalValueMembers = new OriginalValueMembers(false, metadataWorkspace, ef);

Making the Entity track each property change instead of just tracking that the Entity changed.

And also

context.ObjectStateManager.ChangeObjectState(entity, EntityState.Unchanged);

After making these changes I got the desired result of SQL statement with only the modified values/properties in the UPDATE statement. However, there was a strange side effect. When updating a nullable INT property from null to something other than null, the change of that was ignored by Entity Framework. The Self-Tracking Models show the change in the ChangeTracker with the accurate OriginalValue null, but when Entity Framework tried to generate the UPDATE SQL it did not see that property change if the original value null and the new value is not null. I worked if the original value was not null and value gets changed.

It seems to work ok on a string property going from null to a non-null value, but int? is not working.

Does anyone have any ideas?

like image 703
John Egbert Avatar asked Sep 09 '10 23:09

John Egbert


People also ask

Which function of DbContext is used to update the changes done thru entity framework to the database?

Persisting Data: Performs the Insert, Update and Delete operations to the database, based on entity states.

Is part of a key and so Cannot be modified or marked as modified to change the principal?

{property}' is part of a key and so cannot be modified or marked as modified. To change the principal of an existing entity with an identifying foreign key, first delete the dependent and invoke 'SaveChanges', and then associate the dependent with the new principal.


1 Answers

If helpful, have found post that fixes this: fix update of nullable column.

like image 183
David Clements Avatar answered Sep 22 '22 19:09

David Clements