title: Loading MetaData in Aspnet Core
body: <p>I'm building a project in MVC template using AspNet Core.</p>
  
  <p>I've used Entity Framework and I've scaffolded an existing DB. Now, I want to add some Data Annotations to some class, but I don't wanna edit the class autogenerated by the scaffolding, so I've tried with the Metadata and the overriding of an existing method, the <code>saveChanges</code>.</p>
  
  <p><strong>Users.cs autogenerated by Scaffolding</strong></p>
  
  <pre><code>public partial class Users
  {
      public int UserId { get; set; }
      ...
      // If I have [MaxLength(5, ErrorMessage = "Too short")] here, it works
      public string Email { get; set; }
  }
  </code></pre>
  
  <p><strong>UsersMetadata.cs</strong> (also tried Users.Metadata.cs or else, nothing changed)</p>
  
  <pre><code>[ModelMetadataType(typeof(UsersModelMetaData))]
  public partial class Users { }
  
  public class UsersModelMetaData
  {
      [MaxLength(5, ErrorMessage = "Too short")]
      public string Email { get; set; }
  }
  </code></pre>
  
  <p><strong>MyContext : DbContext Class</strong></p>
  
  <pre><code>public override int SaveChanges()
  {
      var entities = from e in ChangeTracker.Entries()
                     where e.State == EntityState.Added
                         || e.State == EntityState.Modified
                     select e.Entity;
      foreach (var entity in entities)
      {               
      var validationContext = new ValidationContext(entity);
          Validator.ValidateObject(entity, validationContext, validateAllProperties: true);
      }
  
      return base.SaveChanges();
  }
  </code></pre>
  
  <p>So, even if this seems to be the correct solution (i've search all morning), it doesn't work: the problem seems to be that the Data Annotation inside <code>UsersModelMetaData</code> aren't read, because if I put the Data Annotation directly in <code>Users.cs</code> file, method <code>saveChanges()</code> will  throw an exception.</p>
  
  <p>I did found this solution -> <a href="https://stackoverflow.com/a/30127682/6070423">https://stackoverflow.com/a/30127682/6070423</a> &lt;- but it's based on AspNet, and using AspNet Core I cannot use <code>AssociatedMetadataTypeTypeDescriptionProvider</code>.</p>
  
  <p>Any idea how I could resolve this?</p>