简体   繁体   English

检测实体框架 EntityObject 上的哪些属性发生了变化

[英]Detect which properties changed on an Entity Framework EntityObject

I want to read changes within an EntityObject for inclusion in a report.我想读取EntityObject更改以包含在报告中。

For example:例如:

Name: Before After名称: 之前 之后

Location: Before After地点: 之前 之后

Is there a generic way to do this?有没有通用的方法来做到这一点? I'm using EF4 with default entity class generation (not POCO).我将 EF4 与默认实体类生成(不是 POCO)一起使用。

These entities will be attached, so they should be being tracked for changes.这些实体将被附加,因此应该跟踪它们的更改。 I cannot see a means to do this via the IEntityWithChangeTracker interface.我看不到通过IEntityWithChangeTracker接口执行此操作的方法。

Traversing navigation properties would be nice, but it'd be enough of a win to just report upon changed primitive properties.遍历导航属性会很好,但是仅仅报告更改的原始属性就足够了。

You can retrieve ObjectStateEntry for your entity and check contents of CurrentValues and OriginalValues .您可以检索实体的ObjectStateEntry并检查CurrentValuesOriginalValues内容。 Try this (untested):试试这个(未经测试):

ObjectStateEntry entry = objectContext.ObjectStateManager.GetObjectStateEntry(entity);
foreach (string property in entry.GetModifiedProperties()) {
    object oldValue = entry.OriginalValues[property];
    object newValue = entry.CurrentValues[property];
}

This will not handle navigation properties and I'm not sure how it would work with complex types.这不会处理导航属性,我不确定它如何处理复杂类型。

In addition to Ladislav Mrnka's suggestion: Not really generic, but at least a possible solution: Code Generation and T4 Text Templates .除了 Ladislav Mrnka 的建议:不是真正通用的,但至少是一个可能的解决方案:代码生成和 T4 文本模板 This allows you to add your own custom logic to each entity when the models are generated.这允许您在生成模型时将自己的自定义逻辑添加到每个实体。

In your case, you could implement the needed traversing functionality to check the navigation properties.在您的情况下,您可以实现所需的遍历功能来检查导航属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM