2014-06-09 2 views
3

Entity Framework에서 감사 가능한 데이터 저장소를 구현하려고합니다. 내 의도는 주어진 시점에서 모든 기록의 상태에 대한 기록을 유지하는 것입니다. 이를 위해서는 모든 delete 문을 업데이트 및 모든 update 문으로 업데이트하여 + insert로 변환해야합니다.Entity Framework CommandTree 인터셉터로 데이터베이스 명령 추가

나는 인터셉터의 기본 설정을 위해 TechEd 2014 EF6 soft delete session 비디오를 따라 갔지만, 어떻게 진행해야할지 모르겠습니다. 쿼리, 삭제 및 삽입에 대한 유효한 사례가 있지만 업데이트가 까다 롭습니다. 지금까지 내가, 하나는 TreeCreated 방법 내의 현재 Result 수정할 수 있습니다 말할 수

public void TreeCreated(DbCommandTreeInterceptionContext interceptionContext) 
{ 
    if (interceptionContext.OriginalResult.DataSpace == DataSpace.SSpace) 
    { 
     //other query interceptors 

     var updateCommand = interceptionContext.OriginalResult as DbUpdateCommandTree; 
     if (updateCommand != null) 
     { 
      //I modify the command to soft delete the current record 
      //(This is pseudo code to replace to verbose EF exp builder code) 
      var newClause = GetNewSoftDeleteClause(updateCommand); 
      interceptionContext.Result = GetUpdateCommandTree(updateCommand, newClause); 

      //Here is where I want to insert a new command into the tree 
      //and copy over the data to a new record 
     } 
    } 
} 

,하지만 난에 새 명령을 삽입 할 수있는 방법을 찾을 수 없습니다 :

다음은 방법의 기본 구조입니다 문맥. 인터셉터가 단일 행 작업 만 처리하는 것처럼 보였으므로 TreeCreated 메소드 내에서 내가하고 싶은 일이 불가능하다고 생각하기 시작했습니다.

데이터베이스 트리거를 사용하지 않고 인터셉터를 사용하여 수행하려는 작업을 수행 할 수있는 방법이 있습니까?

답변

0

이 경우 savechanges()을 AppicationDbContext에 덮어 쓸 수 있습니다. inbuilt 속성 ChangeTracker을 사용하여 업데이트 할 개체를 찾은 다음 삽입해야하는 새 개체를 첨부 할 수 있습니다.

public override int SaveChanges() 
    { 
     List<DbEntityEntry> dbEntityEntries= ChangeTracker.Entries() 
       .Where(e => e.Entity is Person && e.State == EntityState.Modified) 
       .ToList() 

     foreach(var dbEntityEntrie in dbEntityEntries) 
     { 
      var person = (Person)addedCourse.Entity; 
      var log= new Log() 
       { 
        Name=person.Name; 
       } 
      Logs.Add(log); 
     } 

     return base.SaveChanges(); 
    } 

상속 및 제네릭을 사용하여이 코드를 리팩터링 할 수 있습니다.

관련 문제