EF使用过程中,有时候提示字段异常了,但是不知道是哪个字段,这个时候就需要捕捉是哪个字段验证不通过,方法如下:
- using (NorthwindEntities ctx = new NorthwindEntities())
- {
- try
- {
- //ctx.Employees.Attach(entity);
- ctx.Entry(entity).State = System.Data.EntityState.Modified;
- return ctx.SaveChanges();
- }
- catch (DbEntityValidationException ex)
- {
- foreach (var item in ex.EntityValidationErrors)
- {
- foreach (var item2 in item.ValidationErrors)
- {
- error = string.Format("{0}:{1}\r\n", item2.PropertyName, item2.ErrorMessage);
- }
- }
- }