如何让实体框架仅更新生成的 SQL 中修改的属性?
我将实体框架与自我跟踪实体 T4 模板结合使用,默认情况下它将生成一个 SQL 查询,在 UPDATE 语句中设置实体上的所有属性。我只想要一个包含修改的属性的 UPDATE 语句。
我按照书中指定的方式修改了 T4 模板: 实体框架食谱:问题解决方法第 503 页。
我在 T4 模板中更改为这一行:
OriginalValueMembers originalValueMembers = new OriginalValueMembers(false, metadataWorkspace, ef);
使实体跟踪每个属性更改,而不仅仅是跟踪实体更改。
并且
context.ObjectStateManager.ChangeObjectState(entity, EntityState.Unchanged);
在进行这些更改之后,我得到了 SQL 语句的所需结果,仅在 UPDATE 语句中修改了值/属性。然而,有一个奇怪的副作用。将可为 null 的 INT 属性从 null 更新为 null 以外的值时,实体框架会忽略该更改。自我跟踪模型以准确的 OriginalValue null 显示 ChangeTracker 中的更改,但是当实体框架尝试生成 UPDATE SQL 时,如果原始值 null 并且新值不为 null,则它不会看到属性更改。如果原始值不为空并且值发生变化,我就工作。
它似乎可以在从 null 到非 null 值的字符串属性上正常工作,但是 int 呢?不工作。
有人有什么想法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果有帮助,请找到解决此问题的帖子:修复可为空列的更新。
If helpful, have found post that fixes this: fix update of nullable column.