1. 程式人生 > >EntityFramework 數據校驗異常處理

EntityFramework 數據校驗異常處理

ram ember ber exception nbsp mes 處理 err ESS

 1 public void Insert(PageHost entity)
 2 {
 3     try
 4     {
 5         db.pagehost.Add(entity);
 6         db.SaveChanges();
 7     }
 8     catch (DbEntityValidationException ep)
 9     {
10         CatchException(ep);
11     }
12     catch (Exception ep)
13     {
14         throw ep;
15     }
16 } 17 18 private void CatchException(DbEntityValidationException ep) 19 { 20 StringBuilder sb = new StringBuilder(); 21 foreach (DbEntityValidationResult item in ep.EntityValidationErrors) 22 { 23 foreach (string pp in item.Entry.OriginalValues.PropertyNames) 24 { 25 sb.AppendLine(item.Entry.Member(pp).CurrentValue.ToString());
26 } 27 foreach (DbValidationError i in item.ValidationErrors) 28 { 29 throw new Exception(string.Format("{0}\t{1}\t{2}", i.PropertyName, i.ErrorMessage, sb.ToString())); 30 } 31 } 32 }

EntityFramework 數據校驗異常處理