0

n-n 관계의 DbContext/ObjectContext와 함께 CustomersCustomerCategories이 있다고 가정합니다. 나는 AuditLog 테이블에도 관계 상태를 유지하고 싶습니다. 나는 규칙적인 경우에 다음과 같은 코드에 의해이 도달 할 수 있습니다 :관계가있는 DbContext ChangeTracker 문제

관계를 가져 오는

: 다음 코드로 키의 다음 코드에 의해 ChangeTracker의 상태를 관련 기관 모두 찾아 다음

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

및 '를

(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 

관련 고객 또는 관련 CustomerCategories가 새로 추가되어 위 코드가 null을 반환하는 경우를 제외하고는 모두 정상입니다. 그래서 관련 엔티티를 찾을 수 없습니다.

관련 엔티티를 제대로 찾을 수 있습니까?

답변

0

마지막으로 두 시간 후에 간단한 해결책을 발견했습니다. GetObjectByKey ObjectContext에 있고 DbContext에없는 메소드! 엔티티 참조로 전체 컨텍스트를 검색합니다. 그래서 위의 코드 대신 코드를 사용했습니다.

objectContext.GetObjectByKey((dbEntry.CurrentValues.GetValue(0) as EntityKey)); 
objectContext.GetObjectByKey((dbEntry.CurrentValues.GetValue(1) as EntityKey));