user386167
user386167

Reputation:

DBEntityValidationException not being "cleared"

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.

Upvotes: 4

Views: 1113

Answers (2)

Holt Mansfield
Holt Mansfield

Reputation: 119

Two really good answers here. This standalone validation is fantastic. I've been looking for this.

This is very useful for any batch operations.

So use the standalone validation or if you're catching the DBEntityValidationException, then clear the invalid entity from the local cache of the DbContext.

Upvotes: 0

user386167
user386167

Reputation:

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:

var results = new List<ValidationResults>();
Validator.TryValidateObject(entity, new ValidationContext(entity, null, null), results, true);

The problem was that it was actually adding the invalid entity to the set, so it kept throwing the exception on subsequent attempts. Thanks!

Upvotes: 4

Related Questions