title: Entity Framework Regex match and replace
body: <p>I'm working on a database system, where I would like to validate a few properties during any kind of modification of the instance. In this case, we're talking about a "Person" object, that stores the following information:</p>
  
  <ul>
  <li>ID (generated by EF) </li>
  <li>First name</li>
  <li>Last name </li>
  <li>Address</li>
  <li>Phone number</li>
  </ul>
  
  <p>As I'm using Entity Framework's Code First way of solving this problem, all of these have to be properties that are marked for storage (DataMember, Required annotations).
  Now, the problem is, that while I can use the RegexStringValidator annotation for validating the phone number and address properties, I want to normalize the phone number one. It can accept multiple formats, for user convenience.</p>
  
  <p>This is my current code:</p>
  
  <pre><code>    [DataContract]
      public class Person
      {
          [Key, Required, DataMember, Column(Order = 0)]
          public int ID { get; set; }
  
          [Required, DataMember]
          public String FName { get; set; }
          [Required, DataMember]
          public String LName { get; set; }
  
          [Required, DataMember]
          [RegexStringValidator(@"(\+45|\+45\s|)(\d{2}(\s|)){4}")]
          public String Phone { get; set; }
          [DataMember]
          public String Address { get; set; }
      }
  </code></pre>
  
  <p>(I do realize that I don't need the DataMember for every property, but I had some properties that weren't stored in the database, cut from here, as they're not related to the issue)</p>
  
  <p>So, the normalization. This Regexp can accept any kind of danish phone number, formatted in any way (standard danish format is +45 followed by four groups of two digits, e.g. +45 11 22 33 44, but +45 11223344, +45 1122 3344, 11 22 33 44, 1122 3344 and 11223344 are all acceptable and used formats), but I want the output to be in the last one: eight digits without whitespace, or +45 in front of it. This is to make it easier to search for the user using the phone number.</p>
  
  <p>What would be the preferred way of solving this problem? I was first thinking about placing all validation in the setter, then doing a Regex.Replace to generate the normalized phone number. But after some research I saw that many were discouraging such actions, and all of the code sample was about an existing private field and its updater. By my knowledge, it is not possible using EF. </p>
  
  <p>My other idea was using a transitional/intermediate class, that would do the conversion and validation, then it would create a new instance of the EF-version, and pass it to the DbContext. This, while making it a working solution, would increase the complexity and the response speed of the applications using it.</p>
  
  <p>Is there any other way of solving such validation/conversion within an EF-enabled class?</p>