title: T4 Self Tracking Entities And Model Validation
body: <p>I'm using <a href="http://msdn.microsoft.com/en-us/library/ff407090.aspx" rel="nofollow noreferrer">EF4.x Self Tracking Entities</a> in my project and am trying to achieve Model Validation in my MVC4 web application, however, my Model State always seems to be Valid. I'm using T4 templates to generate my "buddy" classes. Below is an example of one of the STE's and its buddy:</p>
  
  <p>STE - generated using T4:</p>
  
  <pre><code>[DataContract(IsReference = true)]
  [KnownType(typeof(Filing))]
  public partial class FilingHistory: IObjectWithChangeTracker, INotifyPropertyChanged
  {
     public int FilingHistoryId 
     {
       //Snipped for Brevity
     }
     // Navigation, ChangeTracking, Association Fix up snipped
  }
  </code></pre>
  
  <p>Here is the Buddy Class generated also via a T4 template I wrote:</p>
  
  <pre><code>[MetadataType(typeof(FilingHistoryMetaData))]
  public partial class FilingHistory
    {
      // Partial Class 
    }
  
  public class FilingHistoryMetaData
  {           
     [Display(Name = "Filing History Id")]
     [Required(ErrorMessage = "Filing History Id is Required.")]
     int FilingHistoryId { get; set; }    
     // Other properties snipped for Brevity
  }
  </code></pre>
  
  <p>I'm going to exclude the key's from each MetaData class because those will be created automatically (just as an fyi). Also, the namespaces for the STE, the empty partial and the buddy class are <strong>identical</strong></p>
  
  <p>When I create a simple controller in MVC4 just to test it out, with a Create Template, on the HttpPost Action of Create I have some code as shown below:</p>
  
  <pre><code>[HttpPost]
  public ActionResult Create(FilingHistory filingHistoryToCreate)
   {
      if (ModelState.IsValid)  // THIS IS ALWAYS TRUE! even if i pass nothing&lt;----
      {
              return Redirect("/");
      }
  
     return View(filingHistoryToCreate);
  }
  </code></pre>
  
  <p>I read through a bunch of SO links and even went through MSDN, and I think I have everything setup correctly, i.e. namespaces are fine so there is no naked partial class stuff going on.</p>
  
  <p>When my view renders I leave all the textboxes empty, I set a breakpoint to inspect by entity and nothing has been set, yet the model is valid. I also tested by entering some garbage into the textboxes to ensure the model binding was working fine, and it was...</p>
  
  <p>I tried also testing using a console application, and I found out that you have to take an additional step of <a href="https://stackoverflow.com/questions/1755340/validate-data-using-dataannotations-with-wpf-entity-framework">registering the MetaData type</a>, but I beleive in MVC this isnt required. In case it helps anyone - the console app and registering meta data type didn't work for me either, so I'm thinking my buddy class may be the culprit?</p>