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

1

7

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?

Design answered 9/9, 2010 at 23:23 Comment(4)
If you post code or XML, please highlight those lines in the text editor and click on the "code" button (101 010) on the editor toolbar to nicely format and syntax highlight it!Incomplete
The STE template may have a bug. This discussion may help #3599050Chery
I don't have a foreign key involved with the table I am using. It's just 1 Entity with no Foreign keys. Your link above appears to be the same problem, but still no solution.Design
Do you know how to do this in EF5? I don't find the above mentioned lines in the Context.tt fileChromatogram
H
1

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

Hardhearted answered 6/12, 2010 at 3:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.