title: Entity Framework Database First Automatically Validate Max Length for Properties
body: <p>I'm using EF Database First with an existing legacy database. Almost every field has a maxlength value in the database, and I can view this value in the .edmx file.</p>
  
  <p>For example, on of the fields <code>CCSTATUS</code> is <code>nvarchar(20)</code>. When the user inputs more than 20 chars, it clears <code>ModelState.IsValid</code>, but throws an <code>DbEntityValidationException</code> on <code>db.SaveChanges()</code>.</p>
  
  <p>For properties that I've added DataAnnotations to, when they fail to validate, they add model errors, which can then be displayed to the user so they can be corrected. I'm aware that I could add <code>[MaxLength(n)]</code> attributes to all of the properties in the Model MetaData classes, but is there a way to have EF add Model Errors instead of throwing <code>DbEntityValidationException</code> when a value is greater than the maxlength for the property?</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>Thanks for the answers everyone. I ended up using <a href="http://msdn.microsoft.com/en-us/data/jj593170.aspx" rel="nofollow">EF Power Tools</a> Reverse Engineer Code First feature to generate Code First models from my database, which included the appropriate maxlength attributes and other necessary annotations.</p>