一个或多个实体的“验证失败"的解决方案.有关更多详细信息,请参阅“EntityValidationErrors"属性." [英] Solution for "Validation failed for one or more entities. See 'EntityValidationErrors' property for more details."
问题描述
我遇到了这个错误,它没有提供任何关于根本原因的详细信息,但我想出了问题所在.我想分享它,以便其他遇到它的人可以成功解决问题.
I encountered this error, it did not provide any detail as to what the root cause was but I figured out what the problem is. I wanted to share it so that others that encounter it might have success in solving the problem.
我有以下课程:
public class BankUser : IdentityUser, IUserProfile
{
#region IUserProfile Members
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Required]
[Display(Name = "Email Address")]
[EmailAddress(ErrorMessage="Invalid Email Address")]
public string Email { get; set; }
[Display(Name = "Time Zone")]
public int TimeZone { get; set; }
public Dictionary<string, string> TimeZoneOptions
{
get
{
Dictionary<string, string> d = new Dictionary<string, string>();
d.Add("(GMT -10:00) Hawaii", "-10");
d.Add("(GMT -9:00) Alaska", "-9");
d.Add("(GMT -8:00) Pacific Time", "-8");
d.Add("(GMT -7:00) Mountain Time", "-7");
d.Add("(GMT -6:00) Central Time", "-6");
d.Add("(GMT -5:00) Eastern Time", "-5");
d.Add("Unknown", "0");
return d;
}
}
[Display(Name = "Phone")]
[Phone(ErrorMessage = "Invalid phone number.")]
[StringLength(10, MinimumLength = 10, ErrorMessage = "Phone number must be 10 characters long.")]
public string Phone { get; set; }
#endregion
}
如您所见,我使用其他属性扩展了 IdentityUser.在尝试创建新用户 UserManager.CreateAsync()
时,我的视图只有用户名和密码作为表单字段.当尝试仅使用用户名和密码提交表单时,系统会尝试验证电子邮件是否已通过,因为它具有必需属性.
As you can see, I extended IdentityUser with additional properties. My view only had UserName and Password as form fields when trying to create a new user UserManager.CreateAsync()
. When trying to submit the form with just the UserName and Password the system would try to validate that Email was passed since it had the Required attribute.
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new BankUser() { UserName = model.UserName };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await SignInAsync(user, isPersistent: false);
return RedirectToAction("Index", "Home");
}
else
{
AddErrors(result);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
推荐答案
解决方案我必须将电子邮件添加为表单中的字段或删除必需属性.一旦我做了其中任何一个,代码就会按预期工作.
Solution I must either add the Email as a field in my form or remove the Required attribute. Once I did either of them the code worked as expected.
希望有所帮助.
这篇关于一个或多个实体的“验证失败"的解决方案.有关更多详细信息,请参阅“EntityValidationErrors"属性."的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!