Faisal Faisal - 27 days ago 18
C# Question

Saving Email and Phone number as encrypted strings

I am trying to save Customer Email and Phone number as encrypted strings to database. Obviously it fails on Entity framework validation, saying not a valid email address or phone number. What could be the best way to handle this situation without compromising validation on the fields? Tried to google it out but not getting anywhere.

The model class fields:

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


Controller action method:

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


Error on output window:

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."


Any help would be highly appreciated.

Answer

You should not be using your Entity Framework classes directly on your controllers. Besides being bad practice, it causes the exact problem you're seeing right now.

Instead, create a separate model class, something like CustomerDto, that has your model validation attributes, and that you will use in your controllers, and map them to your database classes.

Comments