title: Database First Validation
body: <p>I have an auto-generated Entity Framework model. It was generated using a database first approach. The <code>mid_initial</code> column has a database defined constraint that limits the column to a maximum length of 3 characters.</p>
  
  <pre><code>//------------------------------------------------------------------------------
  // &lt;auto-generated&gt;
  //    This code was generated from a template.
  //
  //    Manual changes to this file may cause unexpected behavior in your application.
  //    Manual changes to this file will be overwritten if the code is regenerated.
  // &lt;/auto-generated&gt;
  //------------------------------------------------------------------------------
  
  namespace Agency.DataAccess.RegistrationModel
  {
      using System;
      using System.Collections.Generic;
  
      public partial class Registrant
      {
          public Registrant()
          {
          }
  
          public int id { get; set; }
          public string fname { get; set; }
          public string mid_initial { get; set; }
          public string lname { get; set; }
      }
  }
  </code></pre>
  
  <p>When I try and create a model with a <code>mid_initial</code> greater than 3 characters, a invalid state, <code>ModelState.IsValid</code> is returning true. Because of this <code>db.SaveChanges</code> is then called, which then raises <code>DbEntityValidationException</code>.</p>
  
  <pre><code>[HttpPost]
  public ActionResult Create(Registrant registrant)
  {    
      try
      {
          if (ModelState.IsValid)
          {
              Debug.WriteLine("Entity was valid.");
              db.Registrants.Add(registrant);
              db.SaveChanges();
              return RedirectToAction("Index");
          }
  
          return View("Create", registrant);
      }
      catch (DbEntityValidationException e)
      {
          foreach (var eve in e.EntityValidationErrors)
          {
              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)
              {
                  Debug.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                      ve.PropertyName, ve.ErrorMessage);
              }
          }
          return View(registrant);
      }
  }
  </code></pre>
  
  <p>Why is the <code>ModelState.IsValid</code> method returning true? It would seem that my model is not aware of the maximum length constraint. How do I make it aware?</p>