0

Assume we have Customers and CustomerCategories with n-n relationship DbContext/ObjectContext. I want to maintain the relationship status in AuditLog table too. I can reach this by the following code in regular cases :

fetching relations' status in ChangeTracker by the following code :

foreach (ObjectStateEntry dbEntry in){ 
   objectContext
   .ObjectStateManager
   .GetObjectStateEntries(~EntityState.Detached)
   .Where(o=>o.IsRelationship)

and then finding both related entities' keys by the following codes :

(dbEntry.CurrentValues.GetValue(0) as EntityKey).EntityKeyValues[0].Value //for the key of related entity in customers table 
(dbEntry.CurrentValues.GetValue(1) as EntityKey).EntityKeyValues[0].Value //for the key of related entity in CustomerCategories table 

Everything is ok unless the related Customer or related CustomerCategories added newly which causes the above code returns null. So I cannot find the related entity.

Is there anyway to find the related entity properly?

Mahmoud Moravej
  • 8,705
  • 6
  • 46
  • 65

1 Answers1

0

Finally and after couple of hours I found a simple solution : GetObjectByKey a method which ObjectContext has and DbContext doesn't have! and it search the whole context by entity refrence. So I did it instead of above codes :

 objectContext.GetObjectByKey((dbEntry.CurrentValues.GetValue(0) as EntityKey));
 objectContext.GetObjectByKey((dbEntry.CurrentValues.GetValue(1) as EntityKey));
Mahmoud Moravej
  • 8,705
  • 6
  • 46
  • 65