Reputation:
I receive this error when executing this code:
[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 class:
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()
{
}
}
More details on the exception:
Message "OriginalValues cannot be used for entities in the Added state." string
Stacktrace:
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\Projects\SoccerManager1\SoccerManager1\Models\DAL\UserRepository.cs:regel 48\r\n bij SoccerManager1.Controllers.UserController.Registration(UserModel user) in d:\Stijn\Documenten\Visual Studio 2013\Projects\SoccerManager1\SoccerManager1\Controllers\UserController.cs:regel 72" string
I'm just trying to create a registration page, I don't get it why that I receive this error.
What am I doing wrong here? If this is not enough info that I provided please let me know.
Upvotes: 4
Views: 4167
Reputation: 2178
Validation may have failed for one of your property values. Might be password for which you have set 'StringLength' to 20 and you are inserting encrypted password. Or might be not passing value for some not null fields.
For debugging and finding actual cause you may use following code block in your 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);
}
}
}
Upvotes: 2