Entity Framework System.Data.Entity.Validation.DbEntityValidationException: Validation failed for one or more entities. See ‘EntityValidationErrors’ property for more details

Working in EF 6.0 sometimes I receive “System.Data.Entity.Validation.DbEntityValidationException:Validation failed for one or more entities. See ‘EntityValidationErrors’ property for more details”.
Using the visual studio watcher to try to understand the error, EntityValidationErrors is always null.

Looking on google I found this post:
http://blogs.infosupport.com/improving-dbentityvalidationexception/

I suggest you to make a partial class to your EF data Context, in my case I named it EFContext, and override the SaveChanges method. doing this it’s easy to understand the rights errors.

public partial class EFContext
{
    public override int SaveChanges()
    {
        try
        {
            return base.SaveChanges();
        }
        catch (DbEntityValidationException ex)
        {
            // Retrieve the error messages as a list of strings.
            var errorMessages = ex.EntityValidationErrors
                    .SelectMany(x => x.ValidationErrors)
                    .Select(x => x.ErrorMessage);

            // Join the list to a single string.
            var fullErrorMessage = string.Join("; ", errorMessages);

            // Combine the original exception message with the new one.
            var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);

            // Throw a new DbEntityValidationException with the improved exception message.
            throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);
        }
    }
}
Annunci

Informazioni su Andrea Regoli

Project Manager .Net Developer WPF WP7 Asp.Net c# javascript ajax SQL sharepoint
Questa voce è stata pubblicata in Entity Framework e contrassegnata con , , , . Contrassegna il permalink.

Rispondi

Inserisci i tuoi dati qui sotto o clicca su un'icona per effettuare l'accesso:

Logo WordPress.com

Stai commentando usando il tuo account WordPress.com. Chiudi sessione / Modifica )

Foto Twitter

Stai commentando usando il tuo account Twitter. Chiudi sessione / Modifica )

Foto di Facebook

Stai commentando usando il tuo account Facebook. Chiudi sessione / Modifica )

Google+ photo

Stai commentando usando il tuo account Google+. Chiudi sessione / Modifica )

Connessione a %s...