EntityFramework 数据校验异常处理

 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 }

 

posted @ 2018-08-30 15:08  杨浪  阅读(710)  评论(0编辑  收藏  举报