Validating entities before saving and removing from context

c# entity-framework

Question

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.

1
7
2/15/2016 8:12:51 AM

Accepted Answer

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.

7
2/15/2016 8:48:23 AM

Popular Answer

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;


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow