0

SaveChanges()를 재정의하지만보다 효과적이고 깔끔한 방법이 있는지 알고 싶습니다. 나는 정말로 switch 문을 좋아하지 않는다. 아래에서는 문제를 설명하고 완전한 해결책을 설명했습니다.SaveChanges를 재정 의하여 비즈니스 규칙을 구현하십시오.

감사

문제 사용자가 삽입 뭔가 업데이트를 수행하거나 여러 테이블에 분산 데이터, 업데이트를 열 NewClub.LastActivityDate = DateTime.Now

의 일부를 삭제 할 때마다

모델

public class NewClub 
{ 
//Primary Key 
public int Id { get; set; } 
[...] 
public DateTime LastActivityDate { get; set; } 
} 

public class NewClubProspect 
{ 
    //Primary Key 
    [Key] 
    public int Id { get; set; } 
    //Foreign Key 
    public int NewClubId { get; set; } 
    [..] 
    public virtual NewClub NewClub { get; set; } 
} 

public class NewClubCounselor 
{ 
    [Key] 
     public int Id { get; set; } 
    //Foreign Key 
    public int NewClubId { get; set; } 
    [...] 
    public NewClub NewClub { get; set; } 
} 

// Several more model classes like these ... 

솔루션

public class MyContext : DbContext 
    { 
     public override int SaveChanges() 
     { 
      var entityInfoStr = String.Empty; 
      var saveSuccess = false; 
      var newClubPrimaryKeyId = 0; 

      ObjectContext ctx = ((IObjectContextAdapter)this).ObjectContext; 

      List<ObjectStateEntry> objectStateEntryList = 
      ctx.ObjectStateManager.GetObjectStateEntries(EntityState.Added 
                 | EntityState.Unchanged 
                 | EntityState.Modified 
                 | EntityState.Deleted).ToList(); 

      foreach (ObjectStateEntry entry in objectStateEntryList) 
      { 
       //Skip over relationships 
       if (entry.IsRelationship) continue; 

       //Make sure the entity is a member of the schema: NewClub[...] 
       if (SecurityHelper.IsValidNewClubTableName(entry.EntitySet.Name)) 
       { 

        switch (entry.EntitySet.Name) 
        { 
         case "NewClubs": 
          var nc = entry.Entity as NewClub; 
          if (nc != null) { newClubPrimaryKeyId = nc.Id; } 
          break; 

         case "NewClubBuilders": 
          var ncb = entry.Entity as NewClubBuilder; 
          if (ncb != null) { newClubPrimaryKeyId = ncb.NewClubId; } 
          break; 

         case "NewClubCaseAnswers": 
          var ncca = entry.Entity as NewClubCaseAnswer; 
          if (ncca != null) { newClubPrimaryKeyId = ncca.NewClubId; } 
          break; 

         case "NewClubCommunityLeaders": 
          var nccl = entry.Entity as NewClubCommunityLeader; 
          if (nccl != null) { newClubPrimaryKeyId = nccl.NewClubId; } 
          break; 

         case "NewClubCounselors": 
          var ncc = entry.Entity as NewClubCounselor; 
          if (ncc != null) { newClubPrimaryKeyId = ncc.NewClubId; } 
          break; 

         case "NewClubEmails": 
          var nce = entry.Entity as NewClubEmail; 
          if (nce != null) { newClubPrimaryKeyId = nce.NewClubId; } 
          break; 

         case "NewClubKitOrders": 
          var ncko = entry.Entity as NewClubKitOrder; 
          if (ncko != null) { newClubPrimaryKeyId = ncko.NewClubId; } 
          break; 

         case "NewClubOrganizationChecklists": 
          var ncoc = entry.Entity as NewClubKitOrder; 
          if (ncoc != null) { newClubPrimaryKeyId = ncoc.NewClubId; } 
          break;      

         case "NewClubProspects": 
          var ncp = entry.Entity as NewClubProspect; 
          if (ncp != null) { newClubPrimaryKeyId = ncp.NewClubId; } 
          break; 

         case "NewClubRecruiterTrainingSchedules": 
          var ncrts = entry.Entity as NewClubRecruiterTrainingSchedule; 
          if (ncrts != null) { newClubPrimaryKeyId = ncrts.NewClubId; } 
          break; 

         case "NewClubRecruitingMember": 
          var ncrm = entry.Entity as NewClubRecruitingMember; 
          if (ncrm != null) { newClubPrimaryKeyId = ncrm.NewClubId; } 
          break; 

         case "NewClubRecruitingTeamEvent": 
          var ncrte = entry.Entity as NewClubRecruitingTeamEvent; 
          if (ncrte != null) { newClubPrimaryKeyId = ncrte.NewClubId; } 
          break; 

         case "NewClubSponsor": 
          var ncs = entry.Entity as NewClubSponsor; 
          if (ncs != null) { newClubPrimaryKeyId = ncs.NewClubId; } 
          break; 
        } 

        //Update the NewClub.LastActivityDate column 
        if (newClubPrimaryKeyId > 0) 
        { 
         string q = @"UPDATE NewClub SET LastActivityDate='" + DateTime.Now + "' WHERE Id="+newClubPrimaryKeyId; 


         using (var context = new MyContext()) 
         { 
          var result = context.Database.ExecuteSqlCommand(q); 
         } 


        } 


       } 
      } 

      try 
      { 

       saveSuccess = base.SaveChanges() > 0; 

      } 
      catch (Exception e) 
      { 
       string ex = e.ToString(); 
       //Handle exception 

      } 

      return saveSuccess ? 1 : 0; 
     } 
} 
+1

여기에서 좋은 대답을 얻을 수는 있지만, 그렇지 않은 경우 코드 검토 stackexchange에서 질문하십시오. –

답변

2

첫째,이 목적을 위해 ObjectContext.SavingChanges 이벤트를 처리합니다. 일반적으로 새 값이 데이터베이스에 기록되기 전에 변경된 오브젝트의 유효성을 확인하는 데 사용됩니다.

두 번째로 필요한 조작 집합 인 IClub과 함께 인터페이스를 정의하십시오 (예 : GetClubId()). 필요한 각 엔티티별로 필요한 방식으로 인터페이스를 구현하십시오. 그러면 인터페이스 구현을 확인할 수 있습니다.

foreach (ObjectStateEntry entry in objectStateEntryList) 
{ 
    IClub club = entry.Entity as IClub; 
    if (!entry.IsRelationship && club!=null) 
    { 
      newClubPrimaryKeyId = club.GetClubId(); 
      ... 
    } 
} 

PS. 인터페이스 구현은 엔티티의 부분 클래스에서 수행 할 수 있습니다. 데이터베이스를 먼저 사용하는 경우 t4 템플릿을 조정할 수도 있습니다. 먼저 그들 모두를 조회하지 않기 위해, 여러 개체를 업데이트하는 경우


또한 ObjectContext.Database.ExecuteSqlCommand이 편리합니다. 귀하의 경우 단일 항목을 업데이트하므로 먼저 하나를 쿼리 할 수 ​​있습니다.

var club = context.NewClub.FirstOrDefault(c => c.Id == newClubPrimaryKeyId); 

다음으로 업데이트하십시오.

if (club!=null) 
{ 
    club.LastActivityDate = DateTime.Now; 
} 
+0

먼저 신속하고 간결한 응답에 감사드립니다. ObjectContext.SavingChanges를 구현하기 전에 이러한 클래스를 사용하지 마십시오. 감사합니다 – Slinky

+1

이벤트입니다. 'SaveChanges'를 호출하면 트리거됩니다. 컨텍스트를 생성 한 후 또는 컨텍스트 생성자 내에서 구독하십시오. http://msdn.microsoft.com/en-us/library/system.data.objects.objectcontext.savingchanges%28v=vs.110%29.aspx – Andrew

+0

btw, 당신은 수정 된 엔티티'foreach (objectStateEntry in objectStateEntryList)'를 반복하고 매번 LastActivityDate를 업데이트하는 작업을 수행합니다. 나는'IClub' 인터페이스의 첫 번째 엔티티를 얻는 것이 필요하다고 생각합니다 :'objectStateEntryList.FirstOrDefaut (entry => entry is IClub)', 그리고 그것으로부터 클럽 아이디를 얻는 것. – Andrew

관련 문제