I’m implementing EF 5 in a winforms application and I’m persisting the context (DBContext) in a private field in the form.
I try to add an entity, and because it has some invalid properties, I get a DBEntityValidationException. Then, I set these properties to valid values and try to add it again, and I receive the exact same DBEntityValidationException.
I’m wondering if I need to clear anything? Here’s the code.
private SystemEntities _context = new SystemEntities(); // class field
try
{
Customer customer = ... // set properties here
_context.Customers.Add(customer);
_context.SaveChanges();
}
catch (DBEntityValidationException ex)
{
// get exception even though properties are updated with valid values
}
I do not observe this issue when updating an entity. Many thanks.
The comments pointed me to the right direction. Instead of trying to save the changes and catching the exception, I first get the validation results:
The problem was that it was actually adding the invalid entity to the set, so it kept throwing the exception on subsequent attempts. Thanks!