Validation of objects before saving and removing from context

Is it possible to check the entities that I have already added to the context before I call SaveChanges and remove the invalid ones so that I do not get EntityValidationErrors when saving?

I have a list of about 3 thousand entities, and some of them contain invalid data that prevents all other objects from being saved. I would not want to keep each unit separately, but ignore those that have errors.

Trying to find a solution, I found that you can turn off validation. If I did, would SaveChanges ignore the invalid and save the rest?

 Context.Configuration.ValidateOnSaveEnabled = false; 

I would prefer to call some method to invoke the authentication of the object and remove it from the context. Or perhaps it is even possible to validate an object before I add it to the context? It will be even better.

+5
source share
2 answers

A direct solution checks them before saving and separates these objects from errors.

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

But this is more like a workaround. IMO, you should avoid checking errors earlier (for example, in the api layer) instead of preventing saving in the data layer.

+6
source

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 that, exclude these properties with

  db.Entry(model).State = EntityState.Modified; db.Entry(model).Property(x => x.Token).IsModified = false; 
+1
source

Source: https://habr.com/ru/post/1243033/


All Articles