Search code examples
c#entity-frameworkloggingentity-framework-4

Entity Framework - printing EntityValidationErrors to log


I get the follo0wing error when I print my log

Message: Validation failed for one or more entities. See 'EntityValidationErrors'  
property for more details.; Stack Trace:    at 
System.Data.Entity.Internal.InternalContext.SaveChanges()

The EntityValidationErrors object holds the full detailed error in different nodes. What is the best way to print it?


Solution

  • cleaner syntax:

    catch (System.Data.Entity.Validation.DbEntityValidationException ex)
    {
         Logger.WriteError("{0}{1}Validation errors:{1}{2}", ex, Environment.NewLine, ex.EntityValidationErrors.Select(e => string.Join(Environment.NewLine, e.ValidationErrors.Select(v => string.Format("{0} - {1}", v.PropertyName, v.ErrorMessage)))));
         throw;
    }