gpt4 book ai didi

c# - EntityFramework.dll 中发生类型为 'System.Data.Entity.Validation.DbEntityValidationException' 的第一次机会异常

转载 作者:行者123 更新时间:2023-11-30 12:26:19 37 4
gpt4 key购买 nike

我在执行这段代码时收到这个错误:

[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()
{
}
}

有关异常的更多详细信息:

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);
}
}
}

关于c# - EntityFramework.dll 中发生类型为 'System.Data.Entity.Validation.DbEntityValidationException' 的第一次机会异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29231445/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com