我试图将客户电子邮件和电话号码作为加密字符串保存到数据库。显然它在Entity框架验证上失败,说没有一个有效的电子邮件地址或电话号码。处理这种情况的最佳方式是什么,而不会影响域上的验证?试图谷歌它,但没有得到任何地方。将电子邮件和电话号码保存为加密字符串
模型类字段:
[Required]
[StringLength(256)]
[EmailAddress]
public string Email { get; set; }
[StringLength(256)]
public string Address { get; set; }
[Required]
[Phone]
[Display(Name = "Phone")]
public string PhoneNumber { get; set; }
控制器的操作方法:
if (ModelState.IsValid)
{
try
{
customer.CustomerCode = getNewCode();
customer.PhoneNumber = CryptorEngine.Encrypt(customer.PhoneNumber, true);
customer.Email = CryptorEngine.Encrypt(customer.Email, true);
customer.Address = CryptorEngine.Encrypt(customer.Address, true);
customer.AddedBy = User.Identity.Name;
customer.AddedAt = DateTime.Now;
db.Customers.Add(customer);
db.SaveChanges();
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
System.Diagnostics.Debug.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().Name, eve.Entry.State);
foreach (var ve in eve.ValidationErrors)
{
System.Diagnostics.Debug.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage);
}
}
throw;
}
return RedirectToAction("Index");
}
错误输出窗口上:
Exception thrown:
'System.Data.Entity.Validation.DbEntityValidationException' in EntityFramework.dll
Entity of type "Customer" in state "Added" has the following validation errors:
- Property: "Email", Error: "The Email field is not a valid e-mail address."
- Property: "PhoneNumber", Error: "The Phone field is not a valid phone number."
任何帮助,将不胜感激。
删除[电话]和[电子邮件地址] –
谢谢,将属性移动到视图模型 – Faisal