title: C# How to use DataAnnotations StringLength and SubString to remove text
body: <p>I have a model classes that has a description property with a data annotation attribute of StringLength and length is set to 100 characters.  When this property is more than 100 characters and Entity Framework tries to save this property I get the following error.  </p>
  
  <pre><code> [StringLength(100, ErrorMessage = "Description Max Length is 100")]
          public string Description { get; set; }
  </code></pre>
  
  <p><strong>Error:</strong><br>
  "Validation failed for one or more entities. See 'EntityValidationErrors' property for more details"</p>
  
  <p>I'm not sure if this helps in forming a solution, but I'm using Entity Framework CTP5 and Code First.</p>
  
  <p>What I want to do, is if description is more than 100 characters, then remove characters that are more than 100 characters so that description can be stored and no error will be raised.</p>
  
  <p>I believe I should be able to use the DataAnnotation attribute StringLength manually to help me identify the valid length of description and then use SubString to remove any characters over the valid amount.  </p>
  
  <p>Does anyone know how to use DataAnnotation in this situation? Or is there another options that is available?</p>
  
  <hr>
  
  <p><strong>Update</strong>
  I did what BrokenGlass suggested and here my implementation if:</p>
  
  <pre><code>public static class DataAnnotation
  {
      public static int? GetMaxLengthFromStringLengthAttribute(Type modelClass, string propertyName)
      {
          int? maxLength = null;
          var attribute = modelClass.GetProperties()
                          .Where(p =&gt; p.Name == propertyName)
                          .Single()
                          .GetCustomAttributes(typeof(StringLengthAttribute), true)
                          .Single() as StringLengthAttribute;
  
          if (attribute != null)
              maxLength = attribute.MaximumLength;
  
          return maxLength;
      }
  }
  
  
  int? maxLength = DataAnnotation.GetMaxLengthFromStringLengthAttribute(typeof(Car), "Description");
  
  if(maxLength != null &amp;&amp; car.Description.Length &gt; maxLength)
      car.Description = car.Description.Substring(0, maxLength.Value);
  </code></pre>
  
  <p>BarDev</p>