none
Entity Validation Errors Persist in New DbContext Instance RRS feed

  • Question

  • I'm new to Entity Framework, and I'm using EF 4.3 with Code-First and I'm facing this scenario:

    I have a form where I try to update an existing entity. This update is invalid on purpose.

    So, as expected, an DbEntityValidationException is thrown and it's handled in the DispatcherUnhandledException event in the Application level (it's a WPF application). The validation error is very simple: the field support a maximum length of 15 and I enter 17 characters in order to tweak the exception handling code.

    Now, I need to create a log of this error in my database, so I create a new log entry and try to add it to the data context (it's a new instance of the data context - I use a factory to create DbContext instances per operation).

    At this moment, if I check the DbContext.ChangeTracker, there's no change to the context besides the log entry I just added, but when I call SaveChanges, it throws a DbEntityValidationException not about the new log entry, but about that old invalid entity with 17 character in a 15 char field.

    The weird thing is that if I call SaveChanges without adding the log entry, no exception is thrown.

    Anyone can help me with that?

    Monday, May 14, 2012 5:52 PM

All replies

  • Create a partial class for your Context, there override the following method

     public override int SaveChanges()
     {

    }

    Put return base.SaveChanges(); in the try block and in the catch block make a new context in which you will save

    EntityValidationError and exceptions as needed.

    Regards.

    Friday, May 25, 2012 12:40 PM
  • Hi Rodrigo,

    Does the log entry you are trying to save contain a reference to the modified entity? That would cause it to be attached to the new context and validated when saving. Maybe it references the DbEntityValidationException that was thrown?

    Also you can get the validation errors before calling SaveChanges() by calling GetValidationErrors() and thus avoiding exceptions being thrown.

    Let me know if this helped.

    Friday, May 25, 2012 9:16 PM