执行此代码时收到此错误:
[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()
{
}
}
关于例外的更多细节:
Message “OriginalValues cannot be used for entities in the Added
state.” string
堆栈跟踪:
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
我只是想创建一个注册页面,我不明白我收到此错误的原因.
我在这做错了什么?如果这不是我提供的信息,请告诉我.
最佳答案 您的某个属性值的验证可能失败.可能是您将“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);
}
}
}