Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating entities before saving and removing from context

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.

like image 339
t3chb0t Avatar asked Feb 15 '16 08:02

t3chb0t


2 Answers

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.

like image 159
Cheng Chen Avatar answered Oct 19 '22 10:10

Cheng Chen


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;
like image 32
Shashank Sood Avatar answered Oct 19 '22 11:10

Shashank Sood