2013-04-14 60 views
-2

我正在wpf應用程序中使用實體框架5,並且我希望在添加或刪除或移動或更新實體(CRUD操作)時捕獲所有異常,特別是當存在外鍵時,然後在messageBOX中顯示一條消息以獲取信息。處理實體框架5 CRUD操作的異常

+1

聽起來像是不錯的計劃。 **你試過什麼了?** –

回答

1

我使用這樣的

public DialogResult AttemptToSave(Context Db) 
    { 
     try 
     { 

      Db.SaveChanges(); 
      return DialogResult.OK; 

     } 
     catch (DbEntityValidationException ex) 
      { 

       var msg = String.Format("{0} \n {1}", 
        ex.EntityValidationErrors.First().ValidationErrors.First().ErrorMessage, 
       ChangeInfoMessage(Db)); 

       return MessageBox.Show(text: msg, caption: "Unable to save", buttons: MessageBoxButtons.RetryCancel); 
      } 
    } 




    public string ChangeInfoMessage(Context Db) 
    { 
     var adapter = (IObjectContextAdapter) Db; 
     adapter.ObjectContext.DetectChanges(); 
     int NumAdded = Db.ChangeTracker.Entries().Count(e => e.State == EntityState.Added); 
     int NumModified = Db.ChangeTracker.Entries().Count(e => e.State == EntityState.Modified); 
     int NumDeleted = Db.ChangeTracker.Entries().Count(e => e.State == EntityState.Deleted); 
     return String.Format("{0} additions, {1} changes {2} deletions", NumAdded, NumModified, NumDeleted); 
    } 
1

我用這個,因爲它得到的所有錯誤

public void SaveContext(FTC_Context context) 
{ 
    try { 
     context.SaveChanges(); 
    } catch (Exception ex) { 
     string message = null; 
     string Caption = null; 
     if ((ex) is DbEntityValidationException) { 
      string sb = null; 
      DbEntityValidationException dbException = ex; 
      sb = "The action was cancelled due to the following:" + Constants.vbCrLf; 
      foreach (dbError in dbException.EntityValidationErrors) { 
       foreach (dbObject in dbError.ValidationErrors) { 
        sb += dbObject.ErrorMessage + Constants.vbCrLf; 
       } 
      } 
      message = sb; 
      Caption = "Data Validation Error"; 
     } else { 
      message = ex.Message; 
      Caption = "Database Operation Error"; 
     } 

     object result = MessageBox.Show(message, Caption, MessageBoxButton.OK); 
    } 
}