如何处理System.Data.Entity.Validation.DbEntityValidationException?

use*_*576 14 c# asp.net-mvc entity-framework asp.net-mvc-4

我的应用程序收到以下错误:

EntityFramework.dll中出现"System.Data.Entity.Validation.DbEntityValidationException"类型的异常,但未在用户代码中处理

附加信息:一个或多个实体的验证失败.有关详细信息,请参阅"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");
        }
Run Code Online (Sandbox Code Playgroud)

编辑:用户模型类

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; }

    }
}
Run Code Online (Sandbox Code Playgroud)

我该怎么处理?

RAV*_*ELA 27

为了解决这个错误,我们可以在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);
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)

找到错误后,您可以继续修复它.希望能帮助到你.谢谢


Seb*_*ian 15

存在某种数据库验证,阻止您将数据写入其中.

此解决方案已在此页面上说明:

一个或多个实体的验证失败.有关详细信息,请参阅"EntityValidationErrors"属性

作为您使用.net mvc的额外注意事项,您应该使用System.Diagnostics.Debug.WriteLine()而不是Console.Writeline(),这将在您调试时写入调试输出窗口.因为在运行mvc项目时无法写入控制台.


Rom*_*ias 6

您可以覆盖SaveChanges,以处理此异常并提供更好的异常详细信息。

您可以在上下文类的旁边创建一个“下一个”类……该类的完整代码如下:

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);
                }
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

检查此以获得更多信息:http : //devillers.nl/blog/improving-dbentityvalidationexception/