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}	{1}	{2}", i.PropertyName, i.ErrorMessage, sb.ToString()));
30         }
31     }
32 }
原文地址:https://www.cnblogs.com/yanglang/p/9560309.html