Why does EF 6.01 not give me a DbEntityValidationException Exception?

entity-framework-6 sqlexception

Question

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?

1
1
7/15/2014 4:46:11 AM

Popular Answer

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.

1
7/11/2014 1:58:36 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow