Why does EF 6.01 not give me a DbEntityValidationException Exception?

entity-framework-6 sqlexception

Question

I receive an Exception as expected when I use EF 6.01 SaveChanges to update my SQL 2012 database and have a string field that is too long. As the innermost SqlException just informs me -, what I would like to do is drill into the Exception to discover the offending table and column.

String or binary data would be truncated.

but not which table or column. I am prepared with the following code to alert me to any validation failures, however I do not receive this 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);
        }
    }
}

No column information is provided in any of the nested exceptions that I receive, which are DbUpdateException, UpdateException, and SqlException. I should receive a DbEntityValidationException, so why don't I? Is there a different way to locate the problematic column?

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

Popular Answer

You are receiving an exception that was passed through Entity Framework directly from SQL. According to MSDN, DbEntityValidationException:

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

(Minor emphasis added) Entity Framework's validation is successful, however the actual SQL statement fails because the data you are giving is too long for a column. The column that would be shortened is not returned by SQL either. The notice simply reads, "String or binary data would be shortened."

Your best bet is to check the lengths of the strings in your code against the lengths you set in the SQL columns by going through the 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