如何处理System.Data.Entity.Validation.DbEntityValidationException?
我的应用程序收到以下错误:
EntityFramework.dll中出现“System.Data.Entity.Validation.DbEntityValidationException”类型的exception,但未在用户代码中处理
附加信息:一个或多个实体的validation失败。 有关详细信息,请参阅“EntityValidationErrors”属性。
尝试注册新用户时出现此错误。 ‘db.SaveChanges()’发生错误
这是代码:
public ActionResult Registration(x.Models.User user) { if(ModelState.IsValid) { using(var db = new xDBEntities1()) { var crypto = new SimpleCrypto.PBKDF2(); var encrpPass = crypto.Compute(user.password); var sysUser = db.users.Create(); sysUser.email = user.email; sysUser.username = user.username; sysUser.password = encrpPass; sysUser.premium_credits = 0; sysUser.login_times = 0; sysUser.last_ip = Request.ServerVariables["REMOTE_ADDR"]; sysUser.creation_ip = Request.ServerVariables["REMOTE_ADDR"]; sysUser.banned = 0; sysUser.creation_date = DateTime.Now; sysUser.creation_time = DateTime.Now.TimeOfDay; db.users.Add(sysUser); db.SaveChanges(); } } return RedirectToAction("Index", "Home"); }
编辑:用户模型类
public class User { [Required] [StringLength(50)] [Display(Name="Username: ")] public String username { get; set; } [Required] [DataType(DataType.Password)] [StringLength(50,MinimumLength=6)] [Display(Name="Password: ")] public string password { get; set; } [Required] [EmailAddress] [StringLength(50)] public string email { get; set; } public int phonenumber { get; set; } public int mobilephonenumber { get; set; } } }
我该怎么处理?
存在某种数据库validation,阻止您将数据写入其中。
该解决方案已在此页面上说明:
一个或多个实体的validation失败。 有关详细信息,请参阅“EntityValidationErrors”属性
作为您使用.net mvc的额外注意事项,您应该使用System.Diagnostics.Debug.WriteLine()而不是Console.Writeline(),这将在您调试时写入调试输出窗口。 因为在运行mvc项目时无法写入控制台。
为了解决这个错误,我们可以在try块中包装DatabaseContext对象的SaveChanges()方法,并在Catch循环中包含每个错误,以找出错误的位置。 代码如下。
try { db.SaveChanges(); } catch (DbEntityValidationException ex) { foreach (var entityValidationErrors in ex.EntityValidationErrors) { foreach (var validationError in entityValidationErrors.ValidationErrors) { Response.Write("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage); } } }
找到错误后,您可以继续解决此问题。 希望能帮助到你。 谢谢
即使已经有一个公认的答案,我的经验可能会在将来帮助某人。 对于快速测试,您可以在Configuration.cs文件中检查输入数据库的数据,然后在模型中检查validation条件。 例如,在我的情况下,我会在模型中放入以下validation条件:
[Range(1, 100),DataType(DataType.Currency)] public decimal Price { get; set; }
然后,在Configuration.cs中分配价格:
new Photo{ Title = "Photo 2", DateTaken = DateTime.Parse("2013-6-15"), Genre = "Nature", CameraModel = "Canon", Price = 200 }
这样就创建了EntityFrameworkExceptions并阻止了数据库播种。
您可以覆盖SaveChanges
,以处理此exception并提供更好的exception详细信息。
您可以为上下文类创建一个“下一个”类…该类的完整代码如下:
using System.Data.Entity; using System.Data.Entity.Validation; using System.Linq; namespace MyNamespace { public partial class MyContext : DbContext { // Override base SaveChanges to expand out validation errors so client gets an actually helpful message public override int SaveChanges() { try { return base.SaveChanges(); } catch (DbEntityValidationException ex) { // Retrieve the error messages as a list of strings. var errorMessages = ex.EntityValidationErrors .SelectMany(x => x.ValidationErrors) .Select(x => x.ErrorMessage); // Join the list to a single string. var fullErrorMessage = string.Join("; ", errorMessages); // Combine the original exception message with the new one. var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage); // Throw a new DbEntityValidationException with the improved exception message. throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors); } } } }
查看此信息以获取更多信息: http : //devillers.nl/blog/improving-dbentityvalidationexception/
DB和Model中的密码长度必须> = encrpPass的长度。
检查您尝试将数据保存到的数据库字段的大小。 将字段从varchar(50)更改为varchar(max)对我来说是个窍门。
如果您使用的是Entity Framework,则可能必须删除并添加您更改的表。