C# 类型为'的首次机会例外;System.Data.Entity.Validation.DbEntityValidationException';发生在EntityFramework.dll中
我在执行此代码时收到此错误:C# 类型为'的首次机会例外;System.Data.Entity.Validation.DbEntityValidationException';发生在EntityFramework.dll中,c#,asp.net-mvc,entity-framework,C#,Asp.net Mvc,Entity Framework,我在执行此代码时收到此错误: [HttpPost] public ActionResult Registration(UserModel user) { Console.WriteLine("ja"); try { if (ModelState.IsValid) { var crypto
[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);
}
用户模型类:
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不能用于添加的
状态“字符串”
堆栈跟踪:
StackTrace“bij
System.Data.Entity.Internal.InternalContext.SaveChanges()\r\n bij
System.Data.Entity.Internal.LazyInternalContext.SaveChanges()\r\nbij 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);
}
}
}
可能重复:这确实是密码,但我知道它超出了20的限制,我只是按照YouTube lol的示例代码,他没有得到任何错误。没关系,谢谢@HardUser,很高兴它有帮助:)