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

[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不能用于已添加的实体
  状态。”字符串


堆栈跟踪:


  堆栈跟踪
  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()
  d:\ Stijn \ Documenten \ Visual Studio
  2013 \ Projects \ SoccerManager1 \ SoccerManager1 \ Models \ DAL \ UserRepository.cs:regel
  48 \ r \ n bij
  SoccerManager1.Controllers.UserController.Registration(UserModel用户)
  在d:\ Stijn \ Documenten \ Visual Studio中
  2013 \ Projects \ SoccerManager1 \ SoccerManager1 \ Controllers \ UserController.cs:regel
  72英寸弦


我只是想创建一个注册页面,我不明白为什么我收到此错误。

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

最佳答案

您的其中一个属性值的验证可能失败。可能是您将“ 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);
        }
    }
}

10-04 11:59