9

Is it possible to validate entities that I've already added to the context before I call SaveChanges and remove the invalid ones so that I don't get the EntityValidationErrors on save?

I have a list of about 3k entities and some of them contain invalid data that prevent all other entities to be saved. I wouldn't like to save each entity separately but rather ignore those that have errors.

Trying to find a solution to this I found that you can disable the validation. If I did it, would SaveChanges ignore the invalid ones and save the others?

Context.Configuration.ValidateOnSaveEnabled = false;

I would however prefer to call some method to invoke entity validation and remove it from the context. Or maybe it's even possible to validate an entity before I add it to the context? This would be even better.

2 Answers 2

8

The direct solution is validating them before save, and detach those entities with errors.

foreach (var error in dbContext.GetValidationErrors())
{
    dbContext.Entry(error.Entry).State = EntityState.Detached;
}

But it's more like a workaround. IMO you should avoid the validation errors more earlier (e.g. in the api layer), instead of preventing from saving in the data layer.

1
  • Yes, I mean it like a workaround. I'm going to log the invalid data and look for the bug later but it'd be great if at least some of the data could be saved otherwise one invalid entity paralyses the whole system. It's not always easy to prevent and predict every kind of possible errors. This should be the last resort error detection and prevention.
    – t3chb0t
    Feb 15, 2016 at 8:55
2

Find Model Properties using ViewData.ModelState.Errors;

  foreach (var item in ViewData.ModelState.Keys)
            {
                int err=ViewData.ModelState[item].Errors.Count();
                if (err.Equals(1))
                {
                  // Add property name in a list 
                }
            }

After this Exclude those Properties using

 db.Entry(model).State = EntityState.Modified;
 db.Entry(model).Property(x => x.Token).IsModified = false;
1
  • This is an interesting approach. In this very situation it won't help me but it's good to know that I can disable particular properties. I'll save it for future reference ;-)
    – t3chb0t
    Feb 15, 2016 at 9:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.