我在3層方案中將EntityFramework 4與自我跟蹤實體一起使用。
我的目標是在實體被保存回服務器時檢測ObjectContext的SavingChanges處理程序中的修改後的屬性。3層方案中的EntityFramework的ObjectStateEntry.GetModifiedProperties
需要注意的是:
- 這是一個3層的情況;所以自我跟蹤的實體保存在另一個ObjectContext中,而不是從
- 中獲取的實體,自調實體在調用SaveChanges之前已附加到上下文,並且所有更改均按預期保存。
這是我做跟蹤修改的屬性:
var objectStateManager = objectContext.ObjectStateManager; var modifiedObjectStateEntries = objectStateManager .GetObjectStateEntries(EntityState.Modified) .Where(x => !x.IsRelationship); foreach (var modifiedObjectStateEntry in modifiedObjectStateEntries) { // need to refresh from datasource, since this entity was fetched in another context objectContext.Refresh(RefreshMode.ClientWins, modifiedObjectStateEntry.Entity); var modifiedProperties = modifiedObjectStateEntry.GetModifiedProperties(); }
現在,出於某種原因,該modifiedProperties集合包含的所有屬性,而不僅僅是 那些被修改的。任何想法爲什麼這是這種情況?
當我將OriginalValues與CurrentValues進行比較時,所有內容都與預期一致。
var originalValues = modifiedObjectStateEntry.OriginalValues; var currentValues = modifiedObjectStateEntry.CurrentValues; for (int i = 0; i < originalValues.FieldCount; i++) { // this works fine, only diffs are detected if (!Equals(originalValues.GetValue(i), currentValues.GetValue(i))) { } }
任何想法,爲什麼 「modifiedObjectStateEntry.GetModifiedProperties();」在這種情況下會不會像我預期的那樣工作?
感謝您的時間,
公園
你爲什麼這樣做?當你不使用ApplyChanges時,使用自我跟蹤實體有什麼意義? – 2013-02-26 10:40:49
我打電話給ApplyChanges。 我這樣做是爲了審計目的來跟蹤哪些屬性發生了變化。我不想依靠STE的ChangeTracker來做這種審計追蹤,因爲在這個應用程序中並不是所有事情都通過3層STE場景來保存。 – KoenJ 2013-02-26 22:33:11
您能否顯示用於將實體附加到服務器端上下文的代碼? – dmusial 2013-03-01 11:09:01