Milon Sarker
Milon Sarker

Reputation: 478

How to handle System.Data.Entity.Validation.DbEntityValidationException

I wrote this simple code to update my database column.

            using (HRMSEntities context = new HRMSEntities())
        {
            TBL_EMPLOYEE dataTicketInsert = new TBL_EMPLOYEE();
            dataTicketInsert = context.TBL_EMPLOYEE.Where(x => x.Id == inputEmployeeID).FirstOrDefault();
            dataTicketInsert.Ticket = ticketT;
            context.SaveChanges();
        }

Error Message: An exception of type 'System.Data.Entity.Validation.DbEntityValidationException' occurred in EntityFramework.dll but was not handled in user code Additional information: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.

How can I resolve the problem?

Upvotes: 0

Views: 5193

Answers (1)

renakre
renakre

Reputation: 8291

Add the following code to your DbContext class, then in the validation error message, you will be able to see the details of the validation problem:

public override int SaveChanges()
{
        try
        {
            return base.SaveChanges();
        }
        catch (DbEntityValidationException ex)
        {
            var errorMessages = ex.EntityValidationErrors
                    .SelectMany(x => x.ValidationErrors)
                    .Select(x => x.ErrorMessage);

            var fullErrorMessage = string.Join("; ", errorMessages);

            var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);

            throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);
        }
 }

Reference: https://stackoverflow.com/a/15820506/1845408

Upvotes: 1

Related Questions