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?

Answers


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;
            }

Here are some extension methods:
/// <summary>
///     A DbEntityValidationException extension method that formates validation errors to string.
/// </summary>
public static string DbEntityValidationExceptionToString(this DbEntityValidationException e)
{
    var validationErrors = e.DbEntityValidationResultToString();
    var exceptionMessage = string.Format("{0}{1}Validation errors:{1}{2}", e, Environment.NewLine, validationErrors);
    return exceptionMessage;
}

/// <summary>
///     A DbEntityValidationException extension method that aggregate database entity validation results to string.
/// </summary>
public static string DbEntityValidationResultToString(this DbEntityValidationException e)
{
    return e.EntityValidationErrors
            .Select(dbEntityValidationResult => dbEntityValidationResult.DbValidationErrorsToString(dbEntityValidationResult.ValidationErrors))
            .Aggregate(string.Empty, (current, next) => string.Format("{0}{1}{2}", current, Environment.NewLine, next));
}

/// <summary>
///     A DbEntityValidationResult extension method that to strings database validation errors.
/// </summary>
public static string DbValidationErrorsToString(this DbEntityValidationResult dbEntityValidationResult, IEnumerable<DbValidationError> dbValidationErrors)
{
    var entityName = string.Format("[{0}]", dbEntityValidationResult.Entry.Entity.GetType().Name);
    const string indentation = "\t - ";
    var aggregatedValidationErrorMessages = dbValidationErrors.Select(error => string.Format("[{0} - {1}]", error.PropertyName, error.ErrorMessage))
                                           .Aggregate(string.Empty, (current, validationErrorMessage) => current + (Environment.NewLine + indentation + validationErrorMessage));
    return string.Format("{0}{1}", entityName, aggregatedValidationErrorMessages);
}

Usecase 1:

catch(DbEntityValidationException e) {
    Logger.WriteError(e.DbEntityValidationExceptionToString());
    throw;      
}

Should Output:

StackTrace
Validation errores:
[EntityName]
    - [Property - ErrorMessage]
    - [Property - ErrorMessage]
[EntityName2]
    - [Property - ErrorMessage]
    - [Property - ErrorMessage]

Usecase 2:

catch(DbEntityValidationException e) {
    Logger.WriteError(e.DbEntityValidationResultToString());
    throw;      
}

Should Output:

[EntityName]
    - [Property - ErrorMessage]
    - [Property - ErrorMessage]
[EntityName2]
    - [Property - ErrorMessage]
    - [Property - ErrorMessage]

You can try something like this

   foreach (var failure in ex.EntityValidationErrors)
    {
       string validationErrors="";

        foreach (var error in failure.ValidationErrors)
        {
           validationErrors+=error.PropertyName+"  "+error.ErrorMessage;
        }
    }

Need Your Help

Strange issue when adding a service reference to a project that has the JSON.NET library referenced

json visual-studio-2010 wcf json.net service-reference

The project is your standard run-of-the-mill ASP.NET MVC 3 application that communicates with an in house WCF service. Our ASP.NET MVC application references a few external libraries, including the

Cancelling from Facebook Permissions dialog redirects and does not close

facebook login permissions

I am trying to add Facebook login functionality to my web site using Javascript.