How to Find Column Causing “String or binary data would be truncated” Exception in Entity Framework 5.0.

1 Comment

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.

Categories: C#, Entity Framework Tags: Tags: