Reputation: 197
Is it possible to skip invalid values when I'm saving an entity with SaveChanges and save only valid fields?
It's pretty simple to skip on entities level, but I'm not able to find a way of doing that on fields level.
Upvotes: 1
Views: 364
Reputation: 197
Muhammad's answer gave me great idea. The solution is pretty simple:
try
{
context.Entry(objInDB).State = EntityState.Modified;
context.SaveChanges();
}
catch (Exception ex)
{
var exception = ex as DbEntityValidationException;
if (exception != null)
{
exception.EntityValidationErrors.ToList().ForEach(error =>
{
error.ValidationErrors.ToList().ForEach(validationError =>
{
error.Entry.Property(validationError.PropertyName).IsModified = false;
});
});
context.SaveChanges();
}
}
Upvotes: 1