Dave
Dave

Reputation: 1852

Why does EF 6.01 not give me a DbEntityValidationException Exception?

When I update my SQL 2012 database via EF 6.01 SaveChanges, with a string field that is too long, I get an Exception as expected. What I would like to do is drill into the Exception to find the offending table and column as the innermost SqlException merely tells me -

String or binary data would be truncated.

but not which column or table. I have code like below ready to tell me about any validation errors, but do not get such an Exception.

catch (DbEntityValidationException dbEx)
{
    foreach (var validationErrors in dbEx.EntityValidationErrors)
    {
        foreach (var validationError in validationErrors.ValidationErrors)
        {
            Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
        }
    }
}

The Exception I get is nested as DbUpdateException containing an UpdateException containing a SqlException and none of these have any column information. Why do I not get a DbEntityValidationException? Is there any other way to find the offending column?

Upvotes: 1

Views: 1122

Answers (2)

Dave
Dave

Reputation: 1852

Apparently a DbEntityValidationException is not thrown because EF validation is not done for some reason, so I have added this code before doing the SaveChanges (via TxRepository.Commit) and throw my own custom EfValidationException containing the ValidationErrors if there are any. I have tested, and this works allowing me to log the problematic column.

            // validate the changes
            var lTxValidationErrors = TxRepository.mDbContext.GetValidationErrors();
            if (lTxValidationErrors.Count() > 0)
            {
                // these changes will not commit so throw an error
                throw new EfValidationException(lTxValidationErrors);
            }
            else
            {
                // commit the new data to the database
                TxRepository.Commit();
            }

Upvotes: 0

Steven V
Steven V

Reputation: 16595

This exception you're getting is coming directly from SQL, being passed through Entity Framework. From MSDN about DbEntityValidationException:

Represents an exception thrown from SaveChanges() when the validation of entities fails.

(emphasis my own). The validation from Entity Framework is passing, but the actual SQL statement is failing since the data you're passing it is too long for a column. SQL does not return the column that would be truncated either. It's just a plain text message of 'String or binary data would be truncated.'

Your best bet, go through the columns and ensure the lengths on strings in your code match the lengths you have set in the SQL columns.

Upvotes: 1

Related Questions