获取EntityFrameWork返回的错误和ModelState中的错误
都是通过循环才能找到具体的错误信息
具体方法参见这两篇文章:
EntityFrameWork:
http://www.cnblogs.com/shouzheng/archive/2012/04/19/2456817.html
关键部分
1 string error = string.Empty; 2 using (var blog = new Blog()) 3 { 4 Author author = new Author 5 { 6 Name = "ErrorNameForTest" 7 }; 8 blog.Authors.Add(author); 9 10 try 11 { 12 blog.SaveChanges(); 13 } 14 catch (DbEntityValidationException ex) 15 { 16 foreach (var item in ex.EntityValidationErrors) 17 { 18 foreach (var item2 in item.ValidationErrors) 19 { 20 error = string.Format("{0}:{1}\r\n", item2.PropertyName, item2.ErrorMessage); 21 } 22 } 23 } 24 } 25 return error;
另一篇获取ModelState中的错误:
http://www.cnblogs.com/bjs007/archive/2010/12/08/1900734.html
1 代码 2 [HttpPost] 3 public ActionResult CreateComment(Comment comment) 4 { 5 if (!ModelState.IsValid) 6 { 7 List<string> sb = new List<string>(); 8 //获取所有错误的Key 9 List<string> Keys = ModelState.Keys.ToList(); 10 //获取每一个key对应的ModelStateDictionary 11 foreach (var key in Keys) 12 { 13 var errors = ModelState[key].Errors.ToList(); 14 //将错误描述添加到sb中 15 foreach (var error in errors) 16 { 17 sb.Add(error.ErrorMessage); 18 } 19 } 20 return Json(sb); 21 } 22 else 23 { 24 return Json(commentRepository.InsertComment(comment)); 25 } 26 }