2011-05-30 53 views
4

我已經用Elmah和EF4.1 Code First設置了一個項目。Elmah和DbEntityValidationException

該項目投擲System.Data.Entity.Validation.DbEntityValidationException,但Elmah沒有提供足夠的細節來確定哪些驗證失敗。所有這一切都記錄是:

System.Data.Entity.Validation.DbEntityValidationException: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details. 

有沒有一種方法,使ELMAH擴大並記錄EntityValidationErrors財產?

+0

如果您處理此錯誤並突出顯示UI中的錯誤/顯示消息而不會崩潰並記錄此錯誤,那將會更好。 – Eranga 2011-06-01 06:02:49

回答

2
List<IUserFeedback> errors = new List<IUserFeedback>(); 

try 
{ 
    _dbContext.SaveChanges(); 
    Updated(this, HasUnsavedChanges); 
} 
catch (DbEntityValidationException ex) 
{ 
    foreach (var x in ex.EntityValidationErrors) 
    { 
     foreach (var y in x.ValidationErrors) 
     { 
      if (!String.IsNullOrWhiteSpace(y.PropertyName)) 
       errors.Add(new UserFeedback() { 
        FeedbackFlags = TypeOfUserFeedbackFlags.Error, 
        Message = String.Format("Unable to save {0} due to an issue with its \"{1}\" value. The error returned was \"{2}\"",x.Entry.Entity, y.PropertyName, y.ErrorMessage) 
       }); 
      else 
       errors.Add(new UserFeedback() { 
        FeedbackFlags = TypeOfUserFeedbackFlags.Error, 
        Message = String.Format("Unable to save {0} due to the error \"{1}\"", x.Entry, y.ErrorMessage) 
       }); 
     } 
    } 
} 

return errors; 
+0

這是很好,但據我瞭解,最好是沒有異常代碼,我認爲在這裏我們可以使用像IEnumerable validationResults = this.GetValidationErrors();在調用SaveChanges()之前? – Coops 2013-04-15 15:33:33