在使用EF时,报错:
对一个或多个实体的验证失败。有关详细信息,请参见“EntityValidationErrors”属性
添加一个验证方法:
代码:
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using Rongzi.BZone.Functions; using Rongzi.BZone.Common.Util; using System.Data.Entity.Validation; using System.Text; using System.IO; namespace Rongzi.BZone.Controllers.Manage { public class ManageUserInfoApiController : ApiController { RongziBZoneEntities entity = new RongziBZoneEntities(); /// <summary> /// 后台认证用户 /// </summary> /// <param name="req"></param> /// <returns></returns> [HttpPost] public ResponseContext EditCustomerInfo(RequestContext<CustomerInfo> req) { ResponseContext result = new ResponseContext(); var obj = req.Content; if (obj == null) { result.Head.Ret = -; result.Head.Code = ErrCode.ParameterError; return result; } CustomerInfo info = entity.CustomerInfo.Where(x => x.IsDeleted == false).Where(x => x.CustomerID==obj.CustomerID).FirstOrDefault(); if (info == null) { result.Head.Ret = -; result.Head.Code = ErrCode.DataIsnotExist; return result; } info.IdentificationState = obj.IdentificationState; info.IdentificationMemo = obj.IdentificationMemo; info.IsDeleted = obj.IsDeleted; info.UpdateUser = obj.UpdateUser; info.UpdateTime = DateTime.Now; IsValided<CustomerInfo>(info); entity.SaveChanges(); return result; } public bool IsValided<T>(T model) where T : class { DbEntityValidationResult vResult = entity.Entry<T>(model).GetValidationResult(); if (vResult == null) return true; if (vResult.IsValid) return true; StringBuilder builder = new StringBuilder(); foreach (DbValidationError item in vResult.ValidationErrors) { builder.Append("出错字段:" + item.PropertyName); builder.Append("<br/>"); builder.Append("错误描述:" + item.ErrorMessage); builder.Append("<br />"); } throw new Exception("数据验证失败," + builder.ToString()); return false; } #endregion } }
这样就可以直接查出那些错,
我这个就是有个字段customerCard字段长度在数据库中由50改成了200,我看ef是string类型,就没有在意,然后就报错,长度不能超过50
这个也可以直接关掉ef的验证
entity.Configuration.ValidateOnSaveEnabled = false;
这样也可以