title: Custom advanced entity validation with Dynamic Data
body: <p>I'm looking for a solution to perform some custom entity validation (which would require database access, cross-member validation...) when the user saves its changes in a Dynamic Data screen, with Entity Framework.<br>
  The validation is more complex than what I can do with the attributes (it requires an access to the database, etc.)</p>
  
  <p>Can you intercept the SaveChanges call ?<br>
  I tried to override <code>ValidateEntity</code> in the DbContext object, but Dynamic Data doesn't seem to call it (probably because it's using the internal ObjectContext, not sure why), and overriding SaveChanges doesn't help either.<br>
  I don't see any event that I could subscribe to...</p>
  
  <p>The <a href="https://msdn.microsoft.com/en-us/library/ee225428.aspx#Validating">documentation</a> should help :</p>
  
  <blockquote>
    <p>Customize validation for an individual data field by overriding the
    OnValidate method or handling the Validate event, which are invoked
    when any data field is changed. This approach lets you add validation
    and business logic for an individual field. This approach is more
    general than adding validation for an individual field. It is useful
    when the same validation logic can be applied to more than one data
    field. It also lets you perform validation checks that involve
    multiple fields.</p>
  </blockquote>
  
  <p>But I'm using POCO Entity Framework 6 classes so there's no <code>OnValidate</code> method to override, and from what I read this is for LinqToSql, and I can't find the <code>Validate</code> event they mention.  </p>
  
  <p>I tried to subscribe to the <code>SavingChanges</code> event of the inner <code>ObjectContext</code> in the constructor of my DbContext, to call manually the <code>ValidateEntity</code>, but I don't know what to do with the result. If I throw a <code>DbEntityValidationException</code> (or a <code>ValidationException</code> like suggested in <a href="http://xharze.blogspot.fr/2011/06/aspnet-dynamic-data-part-8-customizing.html">this article</a>), ASPNET handle it like any exception (yellow screen).</p>
  
  <p>Implementing <code>IValidatableObject</code> doesn't work either.</p>
  
  <p>I also tried implementing my own <code>DynamicValidator</code> to see what happens, but with no success, it seems to handle the exception (if I override <code>ValidateException</code>, and put a breakpoint, I see it) but it's still bubbled up to the default error handler and displays a yellow screen. I must be missing something.</p>
  
  <p>So, how should you perform complex validation (cross-field, with queries, etc.)  on entities before saving in Dynamic Data / EF ?</p>