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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With