EntityFramework.dll中出现'System.Data.Entity.Validation.DbEntityValidationException'类型的第一次机会异常

时间:2015-03-24 11:28:27

标签: c# asp.net-mvc entity-framework

执行此代码时收到此错误:

[HttpPost]
        public ActionResult Registration(UserModel user)
        {
            Console.WriteLine("ja");
            try
            {

                if (ModelState.IsValid)
                {
                    var crypto = new SimpleCrypto.PBKDF2();
                    var encrpPass = crypto.Compute(user.Password);
                    UserModel newUser = new UserModel(user.Email, encrpPass);
                    newUser.PasswordSalt = crypto.Salt;

                    userRepository.Add(newUser);
                    userRepository.SaveChanges();

                    return RedirectToAction("Index", "Home");
                }
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException ex)
            {

                    Console.WriteLine(ex);
            }


            return View(user);
        }

UserModel类:

public class UserModel
    {
        public int UserModelId { get; set; }
        [Required]
        [EmailAddress]
        [StringLength(150)]
        [Display(Name="Email address: ")]
        public String Email { get; set; }
        [Required]
        [DataType(DataType.Password)]
        [StringLength(20, MinimumLength = 6)]
        [Display(Name = "Password: ")]
        public String Password { get; set; }
        public String PasswordSalt { get; set; }

        public UserModel(String email, String password)
        {
            this.Email = email;
            this.Password = password;
        }

        public UserModel()
        {
        }
    }

有关例外的更多详情:

  

消息" OriginalValues不能用于已添加的实体   状态&#34。串

堆栈跟踪:

  

StackTrace" BIJ   System.Data.Entity.Internal.InternalContext.SaveChanges()\ r \ n bij   System.Data.Entity.Internal.LazyInternalContext.SaveChanges(个)\ r \ n
  bij System.Data.Entity.DbContext.SaveChanges()\ r \ n bij   SoccerManager1.Models.DAL.UserRepository.SaveChanges()in   d:\ Stijn \ Documenten \ Visual Studio   2013 \项目\ SoccerManager1 \ SoccerManager1 \型号\ DAL \ UserRepository.cs:葱   48 \ r \ n bij   SoccerManager1.Controllers.UserController.Registration(UserModel用户)   在d:\ Stijn \ Documenten \ Visual Studio中   2013 \项目\ SoccerManager1 \ SoccerManager1 \ \控制器UserController.cs:葱   72"串

我只是想创建一个注册页面,但我不知道为什么会收到此错误。

我在这里做错了什么?如果这不是我提供的信息,请告诉我。

1 个答案:

答案 0 :(得分:2)

您的某个属性值的验证可能失败。可能是您设置的密码' StringLength'到20,你正在插入加密密码。或者可能没有为某些非空字段传递值。

为了调试和查找实际原因,您可以在catch中使用以下代码块:

catch (System.Data.Entity.Validation.DbEntityValidationException ex)
{
    foreach (var validationErrors in ex.EntityValidationErrors)
    {
        foreach (var validationError in validationErrors.ValidationErrors)
        {
            Console.WriteLine("Property: {0} throws Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
        }
    }
}