I recently encountered an issue with Entity Framework when it would throw “String or binary data would be truncated. The statement has been terminated.” Since the query contained close to 80 fields, I needed an easy way to determine the culprit. Since I already had a class which inherits from DbContext, I added suggested try-catch block in my SaveChanges() override method:
public partial class MyContext : DbContext { public override int SaveChanges() { try { return base.SaveChanges(); } catch (DbEntityValidationException ex) { foreach (var error in ex.EntityValidationErrors) { Console.WriteLine("===================="); Console.WriteLine( "Entity {0} in state {1} has validation errors:", error.Entry.Entity.GetType().Name, error.Entry.State); foreach (var ve in error.ValidationErrors) { Console.WriteLine("\tProperty: {0}, Error: {1}", ve.PropertyName, ve.ErrorMessage); } Console.WriteLine(); } throw; } } }
You have to make sure that you don’t set ValidateOnSaveEnabled to false. It is set to true by default, but sometimes it is useful to disable it to improve performance.
I’m getting the “STRING OR BINARY DATA WOULD BE TRUNCATED” error too but I’m not getting a DbEntityValidationException exception. I’m getting a System.Data.UpdateException. I’m not even updating a record, I’m only inserting so I don’t know why I’m getting an update error.